"""User submission controller for MCP/Skill/Plugin marketplace.""" import json import logging import os import uuid from datetime import datetime from typing import Optional from fastapi import APIRouter, Depends, Request, UploadFile, File, Form, HTTPException from sqlalchemy.orm import Session from services.common.database import get_db from services.common.utils.response_utils import ResponseUtils from services.admin_service.utils.user_utils import UserUtils from services.common import error_msg from services.common.models.submission import Submission from services.common.models.mcp_service import McpService, ChargeType from services.common.models.mcp_tool_api import McpToolApi, HttpMethod from services.admin_service.services.openapi_helper import convert_openapi_for_ai logger = logging.getLogger(__name__) router = APIRouter() UPLOAD_DIR = "/tmp/submission_uploads" os.makedirs(UPLOAD_DIR, exist_ok=True) def _slugify(text: str) -> str: """Convert text to a slug-safe English string (letters, digits, -, _).""" import re s = re.sub(r"[^A-Za-z0-9]+", "-", (text or "").strip()).strip("-").lower() return s or "service" def _unique_slug(db: Session, text: str) -> str: base = _slugify(text) slug = base counter = 1 while db.query(McpService).filter(McpService.slug_name == slug).first(): slug = f"{base}-{counter}" counter += 1 return slug def _publish_mcp_service(db: Session, sub: Submission) -> str: """ Create a market listing (mcp_service + mcp_tool_api rows) from an approved MCP submission. Returns the new service id. Tool definitions come from the uploaded file when it parses as an OpenAPI spec; otherwise the service is published without tools (admin can add them later from the service edit page). """ meta = sub.metadata_json or {} base_url = (meta.get("base_url") or "").strip() if not base_url: raise ValueError("MCP submission is missing base_url") charge_type_raw = (meta.get("charge_type") or "free").strip().lower() try: price = float(meta.get("price") or 0) except (TypeError, ValueError): price = 0.0 try: free_daily_limit = int(meta.get("free_daily_limit")) if meta.get("free_daily_limit") else None except (TypeError, ValueError): free_daily_limit = None if free_daily_limit is not None and free_daily_limit <= 0: free_daily_limit = None service_type = (meta.get("service_type") or "openapi").strip() or "openapi" tags = meta.get("tags") or "" if isinstance(tags, list): tags = ",".join(str(t).strip() for t in tags if str(t).strip()) # Best-effort: parse the uploaded file as an OpenAPI spec to build tool rows. openapi_data = None if sub.file_path and os.path.exists(sub.file_path): try: with open(sub.file_path, "r", encoding="utf-8", errors="ignore") as f: content = f.read() openapi_data = convert_openapi_for_ai(content) if not getattr(openapi_data, "apis", None): openapi_data = None except Exception as e: # noqa: BLE001 - file may not be an OpenAPI doc logger.info("Submission %s file is not an OpenAPI spec: %s", sub.id, e) openapi_data = None service = McpService() service.id = str(uuid.uuid4()) service.name = sub.name service.slug_name = _unique_slug(db, sub.name) desc = (sub.description or "").strip() or sub.name service.short_description = desc[:255] service.long_description = desc service.base_url = base_url service.headers = "[]" service.charge_type = ChargeType.PER_CALL if (charge_type_raw in ("paid", "per_call") and price > 0) else ChargeType.FREE service.price = price if service.charge_type == ChargeType.PER_CALL else 0.0 service.free_daily_limit = free_daily_limit if service.charge_type == ChargeType.FREE else None service.tags = tags service.service_type = service_type service.enabled = 1 # auto-publish: immediately visible in the market db.add(service) db.flush() tool_count = 0 if openapi_data is not None: for api in openapi_data.apis: try: http_method = HttpMethod(api.method) except ValueError: # HEAD/OPTIONS/TRACE are not part of the supported tool enum continue tool = McpToolApi() tool.id = str(uuid.uuid4()) tool.service_id = service.id tool.name = api.summary or f"{api.method} {api.path}" tool.description = api.description or api.summary or tool.name tool.path = api.path tool.method = http_method tool.header_parameters = json.dumps(api.header_parameters) if api.header_parameters else "" tool.query_parameters = json.dumps(api.query_parameters) if api.query_parameters else "" tool.path_parameters = json.dumps(api.path_parameters) if api.path_parameters else "" tool.request_body_schema = json.dumps(api.request_body_schema) if api.request_body_schema else "" tool.response_schema = json.dumps(api.response_schema) if api.response_schema else "" tool.response_examples = json.dumps(api.response_examples) if api.response_examples else "" tool.response_headers = json.dumps(api.response_headers) if api.response_headers else "" tool.operation_examples = json.dumps(api.operation_examples) if api.operation_examples else "" tool.enabled = 1 tool.is_deleted = 0 db.add(tool) tool_count += 1 db.flush() logger.info( "Auto-published submission %s -> service %s (%d tools, base_url=%s)", sub.id, service.id, tool_count, base_url, ) return service.id @router.post("/submission", summary="User submit MCP/Skill/Plugin") async def create_submission( request: Request, type: str = Form(...), name: str = Form(...), description: str = Form(None), file: UploadFile = File(None), base_url: str = Form(None), service_type: str = Form(None), tags: str = Form(None), charge_type: str = Form(None), price: float = Form(None), free_daily_limit: int = Form(None), db: Session = Depends(get_db), ): try: user_id = UserUtils.get_request_user_id(request) except Exception: user_id = None if not user_id: return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION) if type not in ("mcp", "skill", "plugin"): return ResponseUtils.error(error_msg=error_msg.INVALID_PARAMETER) # MCP submissions must declare where the service lives so that approving # the submission can auto-publish a working market listing. base_url = (base_url or "").strip() if type == "mcp" and not base_url: return ResponseUtils.error(message="base_url is required for MCP submissions") file_path = None if file: safe_name = f"{uuid.uuid4()}_{file.filename}" file_path = os.path.join(UPLOAD_DIR, safe_name) with open(file_path, "wb") as f: f.write(await file.read()) metadata = {} if type == "mcp": metadata = { "base_url": base_url, "service_type": (service_type or "openapi").strip() or "openapi", "tags": (tags or "").strip(), "charge_type": (charge_type or "free").strip() or "free", "price": price, "free_daily_limit": free_daily_limit, } sub = Submission( user_id=user_id, type=type, name=name, description=description, file_path=file_path, metadata_json=metadata or None, status="pending", ) db.add(sub) db.commit() db.refresh(sub) return ResponseUtils.success(data={"id": sub.id, "status": sub.status}) @router.get("/submissions", summary="List user submissions") def list_submissions(request: Request, db: Session = Depends(get_db)): try: user_id = UserUtils.get_request_user_id(request) except Exception: user_id = None if not user_id: return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION) subs = db.query(Submission).filter(Submission.user_id == user_id).order_by(Submission.created_at.desc()).all() data = [ { "id": s.id, "type": s.type, "name": s.name, "description": s.description, "status": s.status, "metadata_json": s.metadata_json, "created_at": s.created_at.isoformat() if s.created_at else None, "review_note": s.review_note, } for s in subs ] return ResponseUtils.success(data=data) # Admin endpoints @router.get("/admin/submissions", summary="Admin list submissions") def admin_list_submissions(request: Request, status: str = None, db: Session = Depends(get_db)): if not UserUtils.is_admin(request): return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION) q = db.query(Submission) if status: q = q.filter(Submission.status == status) subs = q.order_by(Submission.created_at.desc()).all() data = [ { "id": s.id, "user_id": s.user_id, "type": s.type, "name": s.name, "description": s.description, "file_path": s.file_path, "metadata_json": s.metadata_json, "status": s.status, "created_at": s.created_at.isoformat() if s.created_at else None, "review_note": s.review_note, "reviewed_at": s.reviewed_at.isoformat() if s.reviewed_at else None, } for s in subs ] return ResponseUtils.success(data=data) @router.put("/admin/submission/{sub_id}/approve", summary="Approve submission (auto-publish to market)") def approve_submission(sub_id: str, request: Request, db: Session = Depends(get_db)): if not UserUtils.is_admin(request): return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION) sub = db.query(Submission).filter(Submission.id == sub_id).first() if not sub: return ResponseUtils.error(error_msg=error_msg.NOT_FOUND) if sub.status != "pending": return ResponseUtils.error(message="Submission has already been processed") service_id = None if sub.type == "mcp": try: service_id = _publish_mcp_service(db, sub) except Exception as e: # noqa: BLE001 - report the exact reason to the admin db.rollback() logger.error("Auto-publish failed for submission %s: %s", sub_id, e) return ResponseUtils.error(error_msg=f"Auto-publish failed: {e}") sub.status = "approved" sub.reviewer_id = UserUtils.get_request_user_id(request) sub.reviewed_at = datetime.utcnow() if service_id: meta = sub.metadata_json or {} meta["published_service_id"] = service_id sub.metadata_json = meta db.commit() return ResponseUtils.success(data={"service_id": service_id}) @router.put("/admin/submission/{sub_id}/reject", summary="Reject submission") def reject_submission(sub_id: str, request: Request, body: dict = None, db: Session = Depends(get_db)): if not UserUtils.is_admin(request): return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION) sub = db.query(Submission).filter(Submission.id == sub_id).first() if not sub: return ResponseUtils.error(error_msg=error_msg.NOT_FOUND) sub.status = "rejected" sub.reviewer_id = UserUtils.get_request_user_id(request) sub.reviewed_at = datetime.utcnow() if body: sub.review_note = body.get("note") db.commit() return ResponseUtils.success()