abdullah9873's picture
Upload main.py with huggingface_hub
691b61d verified
Raw History Blame Contribute Delete
9.29 kB
# /// script
# dependencies = [
# "mcp[cli]",
# "fastapi",
# "uvicorn",
# "faker",
# "typer",
# "sqlalchemy",
# "psycopg2-binary",
# "python-dotenv",
# "sse-starlette",
# ]
# ///
import json
import uuid
import os
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional
from fastapi import FastAPI, Request, Depends, HTTPException
from fastapi.responses import JSONResponse
from mcp.server.fastmcp import FastMCP
from sqlalchemy.orm import Session
from dotenv import load_dotenv
# Import our production-ready components
from engine import MockApiEngine
from database import SessionLocal, MockApiSchema, get_db, init_db
# Load environment variables
load_dotenv()
# ---------------------------------------------------------------------------
# Setup & State
# ---------------------------------------------------------------------------
# Initialize Database
init_db()
# Initialize FastAPI
app = FastAPI(
title="Mock API Service",
description="Production-ready Mock API Service with MCP-over-SSE support."
)
# Initialize the Engine (No arguments needed anymore)
engine = MockApiEngine()
# Health check endpoint (required for Hugging Face Spaces)
@app.get("/")
async def health_check():
return {"status": "running", "service": "Mock API Service", "sse_endpoint": "/mcp/sse"}
# Initialize FastMCP server
mcp = FastMCP("MockAPI")
HOST_URL = os.getenv("HOST_URL", "http://localhost:8000")
MAX_APIS_PER_USER = 10
# Smart defaults for common entity types
DEFAULT_ENTITIES = {
"products": ["id", "name", "price", "category", "image_url", "description"],
"users": ["id", "full_name", "email", "avatar", "address"],
"posts": ["id", "title", "content", "author", "created_at", "thumbnail"],
"orders": ["id", "product_name", "amount", "status", "order_date"],
"comments": ["id", "post_id", "user_name", "comment_text", "created_at"]
}
# ---------------------------------------------------------------------------
# Helper Functions
# ---------------------------------------------------------------------------
def clean_expired_apis_internal(db: Session):
"""Internal helper to clean expired APIs using a DB session."""
now = datetime.utcnow()
expired = db.query(MockApiSchema).filter(MockApiSchema.expires_at < now).all()
for api in expired:
db.delete(api)
if expired:
db.commit()
# ---------------------------------------------------------------------------
# MCP-over-SSE Support
# ---------------------------------------------------------------------------
# Mount the MCP server as an SSE sub-application
# The sse_app() creates two internal routes: /sse and /messages
# By mounting at "/mcp", the full endpoints become:
# - SSE connect: /mcp/sse
# - Messages: /mcp/messages
# Developers connect their AI agents to: https://your-domain/mcp/sse
app.mount("/mcp", mcp.sse_app())
# ---------------------------------------------------------------------------
# Dynamic Mock Routes
# ---------------------------------------------------------------------------
@app.api_route("/mock/{api_id}/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def handle_mock_request(api_id: str, path: str, request: Request, db: Session = Depends(get_db)):
"""
Catch-all route that delegates to the Engine.
"""
api = db.query(MockApiSchema).filter(MockApiSchema.id == api_id).first()
if not api:
return JSONResponse(status_code=404, content={"detail": "Mock API not found or has been deleted."})
# Expiration check
if api.expires_at < datetime.utcnow():
db.delete(api)
db.commit()
return JSONResponse(status_code=404, content={"detail": "Mock API has expired."})
method = request.method
body = None
if method in ["POST", "PUT"]:
try:
body = await request.json()
except:
body = None
result = await engine.handle_request(api_id, path, method, body)
if result is None:
return JSONResponse(status_code=404, content={"detail": f"Path '{path}' not found in this Mock API."})
if isinstance(result, dict) and result.get("error"):
if result["error"] == "Item not found":
return JSONResponse(status_code=404, content={"detail": result["error"]})
return JSONResponse(status_code=400, content={"detail": result["error"]})
return result
# ---------------------------------------------------------------------------
# MCP Tools
# ---------------------------------------------------------------------------
@mcp.tool()
def generate_mock_api(name: str, fields: str = None, user_id: str = "default", ttl_hours: int = 24) -> str:
"""
Generate a mock API for the given 'name' (e.g. 'products').
'fields' is an optional comma-separated list like "id,title,price,image".
"""
with SessionLocal() as db:
clean_expired_apis_internal(db)
user_apis_count = db.query(MockApiSchema).filter(MockApiSchema.user_id == user_id).count()
if user_apis_count >= MAX_APIS_PER_USER:
return json.dumps({
"status": "error",
"message": f"API limit reached. User '{user_id}' already has {MAX_APIS_PER_USER} active APIs."
})
api_id = str(uuid.uuid4())[:8]
entity_name = name.lower().strip()
# Determine fields
field_list = []
if fields:
field_list = [f.strip() for f in fields.split(",") if f.strip()]
elif entity_name in DEFAULT_ENTITIES:
field_list = DEFAULT_ENTITIES[entity_name]
else:
field_list = ["id", "name", "description", "created_at"]
schema = {
"name": f"{name} API",
"entities": [
{
"name": entity_name or "items",
"fields": {f: "string" for f in field_list}
}
]
}
expires_at = datetime.utcnow() + timedelta(hours=ttl_hours)
routes = engine.load_from_schema(api_id, schema, user_id, expires_at)
return json.dumps({
"status": "success",
"mock_id": api_id,
"base_url": f"{HOST_URL}/mock/{api_id}",
"routes": routes,
"expires_at": expires_at.isoformat()
}, indent=2)
@mcp.tool()
def generate_from_schema(name: str, schema_json: str, user_id: str = "default", ttl_hours: int = 24) -> str:
"""
Generate a complex mock API from a provided JSON schema string.
"""
with SessionLocal() as db:
clean_expired_apis_internal(db)
user_apis_count = db.query(MockApiSchema).filter(MockApiSchema.user_id == user_id).count()
if user_apis_count >= MAX_APIS_PER_USER:
return json.dumps({
"status": "error",
"message": f"API limit reached for user '{user_id}'."
})
try:
schema_dict = json.loads(schema_json)
schema_dict["name"] = name
except json.JSONDecodeError as e:
return json.dumps({"status": "error", "message": f"Invalid JSON: {str(e)}"})
api_id = str(uuid.uuid4())[:8]
expires_at = datetime.utcnow() + timedelta(hours=ttl_hours)
routes = engine.load_from_schema(api_id, schema_dict, user_id, expires_at)
return json.dumps({
"status": "success",
"mock_id": api_id,
"base_url": f"{HOST_URL}/mock/{api_id}",
"routes": routes,
"expires_at": expires_at.isoformat()
}, indent=2)
@mcp.tool()
def list_active_mock_apis(user_id: str = None) -> str:
"""List all active generated mock APIs."""
with SessionLocal() as db:
clean_expired_apis_internal(db)
query = db.query(MockApiSchema)
if user_id:
query = query.filter(MockApiSchema.user_id == user_id)
apis = query.all()
response_data = {
api.id: {
"id": api.id,
"name": api.name,
"user_id": api.user_id,
"expires_at": api.expires_at.isoformat()
} for api in apis
}
return json.dumps({"status": "success", "active_apis": response_data}, indent=2)
@mcp.tool()
def delete_mock_api(api_id: str) -> str:
"""Delete a specific mock API by its ID."""
with SessionLocal() as db:
api = db.query(MockApiSchema).filter(MockApiSchema.id == api_id).first()
if api:
db.delete(api)
db.commit()
return json.dumps({"status": "success", "message": f"Deleted Mock API {api_id}"})
return json.dumps({"status": "error", "message": f"Mock API {api_id} not found"})
# ---------------------------------------------------------------------------
# Execution
# ---------------------------------------------------------------------------
if __name__ == "__main__":
mcp.run()