Spaces:
Sleeping
Sleeping
File size: 9,290 Bytes
65f4f15 691b61d 65f4f15 691b61d 65f4f15 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | # /// 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()
|