feat(submission): auto-publish approved submissions and expose review tab
- approving a submission now creates the McpService/McpToolApi records - and records the published service id back on the submission - review console folded into the admin console as a Submissions tab - submit page rewritten around the shared submission API
This commit is contained in:
1 parent
d18adf035b
commit
1fbb6711f2
6 files changed
+517
-77
No files matched your search
@@ -1,55 +1,7 @@
|
||||
"use client";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import React from "react";
|
||||
import { SubmissionsManagement } from "@/components/console/SubmissionsManagement";
|
||||
|
||||
export default function AdminSubmissionsPage() {
|
||||
const [list, setList] = useState<any[]>([]);
|
||||
const [status, setStatus] = useState("pending");
|
||||
|
||||
const load = async () => {
|
||||
const res = await fetch(`/api/submission/admin/submissions?status=${status}`, { credentials: "include" });
|
||||
const data = await res.json();
|
||||
setList(data?.data || []);
|
||||
};
|
||||
|
||||
useEffect(() => { load(); }, [status]);
|
||||
|
||||
const approve = async (id: string) => {
|
||||
await fetch(`/api/submission/admin/submission/${id}/approve`, { method: "PUT", credentials: "include" });
|
||||
load();
|
||||
};
|
||||
const reject = async (id: string) => {
|
||||
await fetch(`/api/submission/admin/submission/${id}/reject`, { method: "PUT", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ note: "rejected" }) });
|
||||
load();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto p-6">
|
||||
<h1 className="text-2xl font-bold mb-4">提交审核</h1>
|
||||
<select value={status} onChange={e => setStatus(e.target.value)} className="border p-2 mb-4">
|
||||
<option value="pending">待审核</option>
|
||||
<option value="approved">已通过</option>
|
||||
<option value="rejected">已拒绝</option>
|
||||
</select>
|
||||
<table className="w-full border">
|
||||
<thead><tr><th>名称</th><th>类型</th><th>状态</th><th>操作</th></tr></thead>
|
||||
<tbody>
|
||||
{list.map((s: any) => (
|
||||
<tr key={s.id} className="border-t">
|
||||
<td className="p-2">{s.name}</td>
|
||||
<td className="p-2">{s.type}</td>
|
||||
<td className="p-2">{s.status}</td>
|
||||
<td className="p-2">
|
||||
{s.status === "pending" && (
|
||||
<>
|
||||
<button onClick={() => approve(s.id)} className="text-green-600 mr-2">通过</button>
|
||||
<button onClick={() => reject(s.id)} className="text-red-600">拒绝</button>
|
||||
</>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
return <SubmissionsManagement />;
|
||||
}
|
||||
@@ -1,40 +1,173 @@
|
||||
"use client";
|
||||
import React, { useState } from "react";
|
||||
import { fetchAPI } from "@/shared/rpc/common-function";
|
||||
|
||||
type SubType = "mcp" | "skill" | "plugin";
|
||||
|
||||
export default function SubmitPage() {
|
||||
const [type, setType] = useState("mcp");
|
||||
const [type, setType] = useState<SubType>("mcp");
|
||||
const [name, setName] = useState("");
|
||||
const [desc, setDesc] = useState("");
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [msg, setMsg] = useState("");
|
||||
const [baseUrl, setBaseUrl] = useState("");
|
||||
const [serviceType, setServiceType] = useState("openapi");
|
||||
const [tags, setTags] = useState("");
|
||||
const [chargeType, setChargeType] = useState<"free" | "paid">("free");
|
||||
const [price, setPrice] = useState("");
|
||||
const [freeDailyLimit, setFreeDailyLimit] = useState("");
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData();
|
||||
fd.append("type", type);
|
||||
fd.append("name", name);
|
||||
if (desc) fd.append("description", desc);
|
||||
if (file) fd.append("file", file);
|
||||
const res = await fetch("/api/submission/submission", { method: "POST", body: fd, credentials: "include" });
|
||||
const data = await res.json();
|
||||
setMsg(JSON.stringify(data));
|
||||
setMsg(null);
|
||||
|
||||
if (typeof window !== "undefined" && !localStorage.getItem("user_token")) {
|
||||
setMsg({ ok: false, text: "请先登录后再提交(右上角登录)" });
|
||||
return;
|
||||
}
|
||||
if (type === "mcp" && !baseUrl.trim()) {
|
||||
setMsg({ ok: false, text: "MCP 服务必须填写服务地址 base_url" });
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("type", type);
|
||||
fd.append("name", name);
|
||||
if (desc) fd.append("description", desc);
|
||||
if (file) fd.append("file", file);
|
||||
if (type === "mcp") {
|
||||
fd.append("base_url", baseUrl.trim());
|
||||
fd.append("service_type", serviceType);
|
||||
if (tags.trim()) fd.append("tags", tags.trim());
|
||||
fd.append("charge_type", chargeType);
|
||||
if (chargeType === "paid" && price) fd.append("price", price);
|
||||
if (chargeType === "free" && freeDailyLimit) fd.append("free_daily_limit", freeDailyLimit);
|
||||
}
|
||||
|
||||
const data = await fetchAPI<{ success: boolean; error_message?: string; data?: { id: string; status: string } }>(
|
||||
"/api/submission/submission",
|
||||
{ method: "POST", body: fd }
|
||||
);
|
||||
if (data?.success) {
|
||||
setMsg({ ok: true, text: "提交成功,等待管理员审核。审核通过后将自动上架到市场。" });
|
||||
setName(""); setDesc(""); setFile(null); setBaseUrl(""); setTags("");
|
||||
} else {
|
||||
setMsg({ ok: false, text: data?.error_message || "提交失败,请稍后重试" });
|
||||
}
|
||||
} catch (err) {
|
||||
setMsg({ ok: false, text: "提交失败:" + (err as Error).message });
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const inputCls = "border p-2 w-full rounded";
|
||||
|
||||
return (
|
||||
<div className="max-w-xl mx-auto p-6">
|
||||
<h1 className="text-2xl font-bold mb-4">上传 MCP / Skill / Plugin</h1>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h1 className="text-2xl font-bold">上传 MCP / Skill / Plugin</h1>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<select value={type} onChange={e => setType(e.target.value)} className="border p-2 w-full">
|
||||
<select value={type} onChange={(e) => setType(e.target.value as SubType)} className={inputCls}>
|
||||
<option value="mcp">MCP 服务</option>
|
||||
<option value="skill">AI 技能</option>
|
||||
<option value="plugin">AI 插件</option>
|
||||
</select>
|
||||
<input value={name} onChange={e => setName(e.target.value)} placeholder="名称" className="border p-2 w-full" required />
|
||||
<textarea value={desc} onChange={e => setDesc(e.target.value)} placeholder="描述" className="border p-2 w-full" />
|
||||
<input type="file" onChange={e => setFile(e.target.files?.[0] || null)} className="border p-2 w-full" />
|
||||
<button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded">提交</button>
|
||||
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="名称" className={inputCls} required />
|
||||
<textarea value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="描述" className={inputCls} rows={3} />
|
||||
|
||||
{type === "mcp" && (
|
||||
<div className="space-y-3 border rounded p-3 bg-gray-50">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">服务地址 base_url *</label>
|
||||
<input
|
||||
value={baseUrl}
|
||||
onChange={(e) => setBaseUrl(e.target.value)}
|
||||
placeholder="http://192.168.1.10:8020"
|
||||
className={inputCls}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">服务类型</label>
|
||||
<select value={serviceType} onChange={(e) => setServiceType(e.target.value)} className={inputCls}>
|
||||
<option value="openapi">openapi(HTTP 接口)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">标签(逗号分隔)</label>
|
||||
<input value={tags} onChange={(e) => setTags(e.target.value)} placeholder="工具, 搜索, 免费" className={inputCls} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">计费方式</label>
|
||||
<select
|
||||
value={chargeType}
|
||||
onChange={(e) => setChargeType(e.target.value as "free" | "paid")}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="free">免费</option>
|
||||
<option value="paid">按次付费</option>
|
||||
</select>
|
||||
</div>
|
||||
{chargeType === "paid" ? (
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">单价(元/次)</label>
|
||||
<input
|
||||
type="number" step="0.01" min="0"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(e.target.value)}
|
||||
placeholder="0.10"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">每日免费次数(留空 = 不限)</label>
|
||||
<input
|
||||
type="number" min="1"
|
||||
value={freeDailyLimit}
|
||||
onChange={(e) => setFreeDailyLimit(e.target.value)}
|
||||
placeholder="100"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
OpenAPI 规范文件(.json,用于自动生成工具列表)
|
||||
</label>
|
||||
<input type="file" onChange={(e) => setFile(e.target.files?.[0] || null)} className={inputCls} />
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
上传后审核通过会自动生成工具;不上传则上架后需在服务管理里手动添加工具。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{type !== "mcp" && (
|
||||
<input type="file" onChange={(e) => setFile(e.target.files?.[0] || null)} className={inputCls} />
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
|
||||
>
|
||||
{submitting ? "提交中..." : "提交"}
|
||||
</button>
|
||||
</form>
|
||||
{msg && <pre className="mt-4 text-sm">{msg}</pre>}
|
||||
|
||||
{msg && (
|
||||
<pre className={`mt-4 text-sm whitespace-pre-wrap ${msg.ok ? "text-green-700" : "text-red-600"}`}>
|
||||
{msg.text}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import UserManagement from "@/components/user-management/UserManagement";
|
||||
import RevenueManagement from "@/components/revenue-management/RevenueManagement";
|
||||
import ConsoleSidebar from "./Sidebar";
|
||||
import { withComponentInjection } from "@/shared/hooks/useComponentInjection";
|
||||
import { Boxes, DollarSign, Home, ServerIcon, Users } from "lucide-react";
|
||||
import { Boxes, DollarSign, Home, Inbox, ServerIcon, Users } from "lucide-react";
|
||||
import OnboardingWelcome, { REQUIRED_TASK_KEYS } from "./OnboardingWelcome";
|
||||
import ConsoleStats from "./ConsoleStats";
|
||||
import SystemSettingsModal from "./SystemSettingsModal";
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
updateAdminOnboardingTasks,
|
||||
} from "@/api/onboard.api";
|
||||
import ResourceGroupManagement from "../resource-group/resourceGroup";
|
||||
import { SubmissionsManagement } from "./SubmissionsManagement";
|
||||
|
||||
const ConsoleContent: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
@@ -37,9 +38,13 @@ const ConsoleContent: React.FC = () => {
|
||||
const tabFromUrl = searchParams.get("tab") as TabKey;
|
||||
if (
|
||||
tabFromUrl &&
|
||||
["mcp-services", "user-management", "revenue-management", "resource-group"].includes(
|
||||
tabFromUrl
|
||||
)
|
||||
[
|
||||
"mcp-services",
|
||||
"user-management",
|
||||
"revenue-management",
|
||||
"resource-group",
|
||||
"submissions",
|
||||
].includes(tabFromUrl)
|
||||
) {
|
||||
return tabFromUrl;
|
||||
}
|
||||
@@ -69,6 +74,12 @@ const ConsoleContent: React.FC = () => {
|
||||
label: t("MCP"),
|
||||
description: t("Manage MCP servers and API tools"),
|
||||
},
|
||||
{
|
||||
key: TabKey.SUBMISSIONS,
|
||||
icon: <Inbox size={18} />,
|
||||
label: t("Submissions"),
|
||||
description: t("Review user submissions and publish to marketplace"),
|
||||
},
|
||||
{
|
||||
key: TabKey.USER_MANAGEMENT,
|
||||
icon: <Users size={18} />,
|
||||
@@ -213,6 +224,12 @@ const ConsoleContent: React.FC = () => {
|
||||
switch (activeTab) {
|
||||
case TabKey.MCP_SERVICES:
|
||||
return <MCPServicesManagement />;
|
||||
case TabKey.SUBMISSIONS:
|
||||
return (
|
||||
<div className="h-full overflow-auto">
|
||||
<SubmissionsManagement />
|
||||
</div>
|
||||
);
|
||||
case TabKey.USER_MANAGEMENT:
|
||||
return (
|
||||
<div className="h-full overflow-auto">
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"use client";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
|
||||
interface Metadata {
|
||||
base_url?: string;
|
||||
service_type?: string;
|
||||
tags?: string;
|
||||
charge_type?: string;
|
||||
price?: number;
|
||||
free_daily_limit?: number | null;
|
||||
published_service_id?: string;
|
||||
}
|
||||
|
||||
interface Submission {
|
||||
id: string;
|
||||
user_id: string;
|
||||
type: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
file_path?: string;
|
||||
metadata_json?: Metadata | null;
|
||||
status: string;
|
||||
created_at?: string;
|
||||
review_note?: string;
|
||||
}
|
||||
|
||||
const statusColor: Record<string, string> = {
|
||||
pending: "bg-yellow-100 text-yellow-800",
|
||||
approved: "bg-green-100 text-green-800",
|
||||
rejected: "bg-red-100 text-red-800",
|
||||
};
|
||||
|
||||
export function SubmissionsManagement() {
|
||||
const [subs, setSubs] = useState<Submission[]>([]);
|
||||
const [filter, setFilter] = useState<string>("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [rejectNote, setRejectNote] = useState<Record<string, string>>({});
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const qs = filter ? `?status=${filter}` : "";
|
||||
// fetchAdminAPI<T> already returns the { success, error_message, data } envelope
|
||||
const response = await fetchAdminAPI<Submission[]>(
|
||||
`/api/submission/admin/submissions${qs}`
|
||||
);
|
||||
if (response?.success === false) {
|
||||
setError(response.error_message || "加载失败");
|
||||
setSubs([]);
|
||||
} else if (response?.data) {
|
||||
setSubs(response.data);
|
||||
} else {
|
||||
setSubs([]);
|
||||
}
|
||||
} catch (err) {
|
||||
setError("加载失败:" + (err as Error).message);
|
||||
setSubs([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { load(); }, [filter]);
|
||||
|
||||
const act = async (id: string, action: "approve" | "reject") => {
|
||||
const body: RequestInit =
|
||||
action === "approve"
|
||||
? { method: "PUT" }
|
||||
: {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ note: rejectNote[id] || "" }),
|
||||
};
|
||||
await fetchAdminAPI(`/api/submission/admin/submission/${id}/${action}`, body);
|
||||
load();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h1 className="text-2xl font-bold">投稿审核</h1>
|
||||
<select value={filter} onChange={(e) => setFilter(e.target.value)} className="border p-2">
|
||||
<option value="">全部</option>
|
||||
<option value="pending">待审核</option>
|
||||
<option value="approved">已通过</option>
|
||||
<option value="rejected">已拒绝</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{error && <div className="mb-4 p-3 bg-red-50 text-red-700 rounded">{error}</div>}
|
||||
{loading && <div className="mb-4 text-gray-500">加载中...</div>}
|
||||
{!loading && !error && subs.length === 0 && (
|
||||
<div className="mb-4 text-gray-500">暂无提交记录</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{subs.map((s) => {
|
||||
const meta = s.metadata_json || {};
|
||||
return (
|
||||
<div key={s.id} className="border rounded p-4 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-semibold">{s.name}</span>
|
||||
<span className="px-2 py-0.5 rounded text-xs">{s.type}</span>
|
||||
<span className={`px-2 py-0.5 rounded text-xs ${statusColor[s.status] || "bg-gray-100"}`}>{s.status}</span>
|
||||
</div>
|
||||
<span className="text-sm text-gray-500">{s.created_at?.slice(0, 19).replace("T", " ")}</span>
|
||||
</div>
|
||||
|
||||
{s.description && <p className="text-sm text-gray-700">{s.description}</p>}
|
||||
|
||||
{s.type === "mcp" && (meta.base_url || meta.tags || meta.charge_type) && (
|
||||
<div className="text-sm text-gray-600 bg-gray-50 rounded p-2 space-y-1">
|
||||
{meta.base_url && <div>服务地址:<code className="text-xs">{meta.base_url}</code></div>}
|
||||
{meta.tags && <div>标签:{meta.tags}</div>}
|
||||
<div>
|
||||
计费:
|
||||
{meta.charge_type === "paid"
|
||||
? `按次付费 ¥${meta.price ?? 0}/次`
|
||||
: `免费${meta.free_daily_limit ? `(每日 ${meta.free_daily_limit} 次)` : "(不限次)"}`}
|
||||
</div>
|
||||
{meta.published_service_id && (
|
||||
<div className="text-green-700">
|
||||
已上架市场,服务 ID:<code className="text-xs">{meta.published_service_id}</code>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{s.file_path && (
|
||||
<div className="text-sm text-gray-500">
|
||||
附件:<code className="text-xs">{s.file_path}</code>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{s.review_note && (
|
||||
<div className="text-sm text-gray-600">审核备注:{s.review_note}</div>
|
||||
)}
|
||||
|
||||
{s.status === "pending" ? (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
value={rejectNote[s.id] || ""}
|
||||
onChange={(e) => setRejectNote({ ...rejectNote, [s.id]: e.target.value })}
|
||||
placeholder="拒绝原因(可选)"
|
||||
className="border p-2 w-full text-sm"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => act(s.id, "approve")}
|
||||
className="bg-green-600 text-white px-3 py-1 rounded text-sm"
|
||||
>
|
||||
通过(自动上架)
|
||||
</button>
|
||||
<button
|
||||
onClick={() => act(s.id, "reject")}
|
||||
className="bg-red-600 text-white px-3 py-1 rounded text-sm"
|
||||
>
|
||||
拒绝
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ export enum TabKey {
|
||||
USER_MANAGEMENT = "user-management",
|
||||
RESOURCE_GROUP = "resource-group",
|
||||
REVENUE_MANAGEMENT = "revenue-management",
|
||||
SUBMISSIONS = "submissions",
|
||||
PAYMENT_CHANNELS = "payment-channels",
|
||||
LOGIN_SETTINGS = "login-settings",
|
||||
SYSTEM_SETTINGS = "system-settings",
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
"""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.common.utils.validation_utils import ValidationUtils
|
||||
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()
|
||||
@@ -18,6 +25,122 @@ 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,
|
||||
@@ -25,6 +148,12 @@ async def create_submission(
|
||||
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:
|
||||
@@ -37,6 +166,12 @@ async def create_submission(
|
||||
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}"
|
||||
@@ -44,12 +179,24 @@ async def create_submission(
|
||||
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)
|
||||
@@ -75,6 +222,7 @@ def list_submissions(request: Request, db: Session = Depends(get_db)):
|
||||
"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,
|
||||
}
|
||||
@@ -101,16 +249,18 @@ def admin_list_submissions(request: Request, status: str = None, db: Session = D
|
||||
"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")
|
||||
@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)
|
||||
@@ -118,12 +268,27 @@ def approve_submission(sub_id: str, request: Request, db: Session = Depends(get_
|
||||
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)
|
||||
from datetime import datetime
|
||||
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()
|
||||
return ResponseUtils.success(data={"service_id": service_id})
|
||||
|
||||
|
||||
@router.put("/admin/submission/{sub_id}/reject", summary="Reject submission")
|
||||
@@ -136,7 +301,6 @@ def reject_submission(sub_id: str, request: Request, body: dict = None, db: Sess
|
||||
return ResponseUtils.error(error_msg=error_msg.NOT_FOUND)
|
||||
sub.status = "rejected"
|
||||
sub.reviewer_id = UserUtils.get_request_user_id(request)
|
||||
from datetime import datetime
|
||||
sub.reviewed_at = datetime.utcnow()
|
||||
if body:
|
||||
sub.review_note = body.get("note")
|
||||
|
||||
Reference in new issue
Block a user