Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b373d143f | ||
|
|
8529ac2e60 | ||
|
|
7f47841fdc | ||
|
|
f5b45af30a | ||
|
|
851d45a573 | ||
|
|
b7a10ca678 | ||
|
|
8f0796c031 |
No files matched your search
@@ -343,3 +343,46 @@ For details, please see the [LICENSE](./LICENSE) file.
|
||||
- [XRoute](https://xroute.ai): The Unified Interface For LLMs, provides better prices, better throughput, and no subscription.
|
||||
|
||||
- [MemU](https://github.com/NevaMind-AI/memU): MemU is an open-source memory framework for AI companions
|
||||
|
||||
---
|
||||
|
||||
## 国内镜像部署(本项目维护,随 Release 更新)
|
||||
|
||||
镜像已双渠道发布,任选其一拉取:
|
||||
|
||||
- 公网:`gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.1`、`jpccr.ccs.tencentyun.com/jinghui/xpack-mcp-market:v1.5.1`
|
||||
- 内网:`192.168.68.19:3200/jinghui/xpack-mcp-market:v1.5.1`
|
||||
|
||||
### 方式一:docker-compose(推荐,带齐全部服务参数)
|
||||
|
||||
```bash
|
||||
git clone http://192.168.68.19:3200/jinghui/xpack-mcp.git && cd xpack-mcp
|
||||
|
||||
# 1) 把 docker-compose.yml 中 xpack-mcp-market 服务的 image 改为公网镜像:
|
||||
# image: xpackai/xpack-mcp-market:zhcn
|
||||
# → image: gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.1
|
||||
|
||||
# 2) 准备环境变量(支付渠道加密密钥,必须改掉示例值)
|
||||
cp .env.example .env && vim .env # 修改 PAYMENT_CONFIG_SECRET_KEY 为自己的 32 字节随机串
|
||||
|
||||
docker compose up -d # 启动 mysql/redis/rabbitmq/market 四个容器
|
||||
```
|
||||
|
||||
注意事项:
|
||||
- `PAYMENT_CONFIG_SECRET_KEY` 缺失时 compose 会直接报错拒绝启动(`.env` 不可删);
|
||||
- 数据库账号、Redis 密码、RabbitMQ 密码在 compose 里已固定,改任何一项都要同步改应用配置;
|
||||
- 数据目录 `./mysql-data` 与容器网络 `172.101.0.0/24` 不要与已有环境冲突。
|
||||
|
||||
### 方式二:docker run(主站单容器)
|
||||
|
||||
前置:MySQL 8.0.37 / Redis 7.2.4 / RabbitMQ 4.1.2 已就绪,且容器与依赖服务同一网络(应用默认按主机名 `xpack-mysql`、`xpack-redis`、`xpack-rabbitmq` 连接)。
|
||||
|
||||
```bash
|
||||
docker run -d --name xpack-mcp-market \
|
||||
--restart always --privileged \
|
||||
-p 8010:80 \
|
||||
-e PAYMENT_CONFIG_SECRET_KEY='<32字节随机串>' \
|
||||
-e PAYMENT_CONFIG_KEY_ID=default \
|
||||
--network <依赖服务所在网络> \
|
||||
gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.1
|
||||
```
|
||||
@@ -328,7 +328,7 @@
|
||||
"Current Balance": "Current Balance",
|
||||
"User recharged successfully": "User recharged successfully",
|
||||
"Please enter a valid amount": "Please enter a valid amount",
|
||||
"Minimum recharge amount is $1": "Minimum recharge amount is $1",
|
||||
"Minimum recharge amount is ¥1": "Minimum recharge amount is ¥1",
|
||||
"User not selected": "User not selected",
|
||||
"Recharge failed": "Recharge failed",
|
||||
"Network error, please try again": "Network error, please try again",
|
||||
|
||||
@@ -330,7 +330,7 @@
|
||||
"Current Balance": "当前余额",
|
||||
"User recharged successfully": "用户充值成功",
|
||||
"Please enter a valid amount": "请输入有效金额",
|
||||
"Minimum recharge amount is $1": "最低充值金额为 $1",
|
||||
"Minimum recharge amount is ¥1": "最低充值金额为 ¥1",
|
||||
"User not selected": "未选择用户",
|
||||
"Recharge failed": "充值失败",
|
||||
"Network error, please try again": "网络错误,请重试",
|
||||
@@ -968,5 +968,12 @@
|
||||
"Example 100": "如 100",
|
||||
"Enter a non-negative integer": "请输入非负整数",
|
||||
"Free call limit saved": "免费调用上限已保存",
|
||||
"Failed to save free call limit": "保存免费调用上限失败"
|
||||
"Failed to save free call limit": "保存免费调用上限失败",
|
||||
"Publish MCP Service": "发布 MCP 服务",
|
||||
"Submit your own MCP service": "提交你的 MCP 服务并上架市场",
|
||||
"My Submissions": "我的提交记录",
|
||||
"No submissions yet": "还没有提交记录",
|
||||
"Pending Review": "待审核",
|
||||
"Approved": "已通过",
|
||||
"Rejected": "已拒绝"
|
||||
}
|
||||
@@ -1,11 +1,34 @@
|
||||
"use client";
|
||||
import React, { useState } from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { fetchAPI } from "@/shared/rpc/common-function";
|
||||
import { useSharedStore } from "@/shared/store/share";
|
||||
|
||||
type SubType = "mcp" | "skill" | "plugin";
|
||||
type SubType = "mcp";
|
||||
|
||||
type SubRecord = {
|
||||
id: string;
|
||||
type: string;
|
||||
name: string;
|
||||
status: string;
|
||||
created_at?: string | null;
|
||||
review_note?: string | null;
|
||||
};
|
||||
|
||||
const TYPE_LABEL: Record<string, string> = {
|
||||
mcp: "MCP 服务",
|
||||
};
|
||||
|
||||
const STATUS_LABEL: Record<string, { text: string; cls: string }> = {
|
||||
pending: { text: "待审核", cls: "bg-yellow-100 text-yellow-800" },
|
||||
approved: { text: "已通过", cls: "bg-green-100 text-green-800" },
|
||||
rejected: { text: "已拒绝", cls: "bg-red-100 text-red-700" },
|
||||
};
|
||||
|
||||
export default function SubmitPage() {
|
||||
const [type, setType] = useState<SubType>("mcp");
|
||||
// 网页登录态存在 zustand store(XPack_Shared),localStorage["user_token"] 只有扩展侧栏才会写,
|
||||
// 用 store 判断才不会把已登录用户误判为未登录
|
||||
const user_token = useSharedStore((s: any) => s.user_token);
|
||||
const type: SubType = "mcp";
|
||||
const [name, setName] = useState("");
|
||||
const [desc, setDesc] = useState("");
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
@@ -17,12 +40,38 @@ export default function SubmitPage() {
|
||||
const [freeDailyLimit, setFreeDailyLimit] = useState("");
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [subs, setSubs] = useState<SubRecord[]>([]);
|
||||
const [loggedIn, setLoggedIn] = useState<boolean | null>(null);
|
||||
|
||||
const loadSubs = async () => {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
const d = await fetchAPI<{ success: boolean; data?: SubRecord[] }>(
|
||||
"/api/submission/submissions",
|
||||
{ method: "GET" }
|
||||
);
|
||||
if (d?.success && Array.isArray(d.data)) {
|
||||
setLoggedIn(true);
|
||||
setSubs(d.data);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
/* 网络异常按未登录处理,不影响提交表单 */
|
||||
}
|
||||
setLoggedIn(false);
|
||||
setSubs([]);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadSubs();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setMsg(null);
|
||||
|
||||
if (typeof window !== "undefined" && !localStorage.getItem("user_token")) {
|
||||
if (typeof window !== "undefined" && !user_token) {
|
||||
setMsg({ ok: false, text: "请先登录后再提交(右上角登录)" });
|
||||
return;
|
||||
}
|
||||
@@ -54,6 +103,7 @@ export default function SubmitPage() {
|
||||
if (data?.success) {
|
||||
setMsg({ ok: true, text: "提交成功,等待管理员审核。审核通过后将自动上架到市场。" });
|
||||
setName(""); setDesc(""); setFile(null); setBaseUrl(""); setTags("");
|
||||
loadSubs();
|
||||
} else {
|
||||
setMsg({ ok: false, text: data?.error_message || "提交失败,请稍后重试" });
|
||||
}
|
||||
@@ -69,16 +119,10 @@ export default function SubmitPage() {
|
||||
return (
|
||||
<div className="max-w-xl mx-auto p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h1 className="text-2xl font-bold">上传 MCP / Skill / Plugin</h1>
|
||||
<h1 className="text-2xl font-bold">上传 MCP 服务</h1>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<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={inputCls} required />
|
||||
<textarea value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="描述" className={inputCls} rows={3} />
|
||||
|
||||
@@ -150,10 +194,6 @@ export default function SubmitPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{type !== "mcp" && (
|
||||
<input type="file" onChange={(e) => setFile(e.target.files?.[0] || null)} className={inputCls} />
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
@@ -168,6 +208,53 @@ export default function SubmitPage() {
|
||||
{msg.text}
|
||||
</pre>
|
||||
)}
|
||||
|
||||
{loggedIn === false && (
|
||||
<p className="mt-6 text-sm text-gray-500">
|
||||
登录后可提交服务并查看审核状态。
|
||||
</p>
|
||||
)}
|
||||
|
||||
{loggedIn && (
|
||||
<div className="mt-8 border rounded p-4 bg-white">
|
||||
<h2 className="text-lg font-semibold mb-3">我的提交记录</h2>
|
||||
{subs.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">还没有提交记录</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{subs.map((s) => {
|
||||
const st = STATUS_LABEL[s.status] || {
|
||||
text: s.status,
|
||||
cls: "bg-gray-100 text-gray-600",
|
||||
};
|
||||
return (
|
||||
<li key={s.id} className="border rounded p-3 text-sm">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-medium truncate">{s.name}</span>
|
||||
<span
|
||||
className={`px-2 py-0.5 rounded text-xs whitespace-nowrap ${st.cls}`}
|
||||
>
|
||||
{st.text}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 mt-1 flex flex-wrap gap-x-4">
|
||||
<span>{TYPE_LABEL[s.type] || s.type}</span>
|
||||
{s.created_at && (
|
||||
<span>{new Date(s.created_at).toLocaleString("zh-CN")}</span>
|
||||
)}
|
||||
</div>
|
||||
{s.review_note && (
|
||||
<div className="text-xs text-orange-600 mt-1">
|
||||
审核备注:{s.review_note}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -233,9 +233,9 @@ const ConsoleStats: React.FC = () => {
|
||||
return transformToChartData(analyticsData);
|
||||
}, [analyticsData]);
|
||||
|
||||
// Format revenue as currency (USD by default)
|
||||
const formatCurrency = (value: number, currency: string = "USD") =>
|
||||
new Intl.NumberFormat("en-US", { style: "currency", currency }).format(
|
||||
// Format revenue as currency (CNY by default)
|
||||
const formatCurrency = (value: number, currency: string = "CNY") =>
|
||||
new Intl.NumberFormat("zh-CN", { style: "currency", currency }).format(
|
||||
value
|
||||
);
|
||||
if (loading) {
|
||||
|
||||
@@ -170,25 +170,25 @@ const AccountBalanceTable: React.FC<AccountBalanceTableProps> = ({ userId, sourc
|
||||
);
|
||||
};
|
||||
|
||||
// 格式化金额,带正负号和美元符号
|
||||
// 格式化金额,带正负号和人民币符号
|
||||
const formatAmount = (amount: string | number): string => {
|
||||
const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
|
||||
if (isNaN(numAmount)) return '$0.00';
|
||||
if (isNaN(numAmount)) return '¥0.00';
|
||||
const absAmount = Math.abs(numAmount).toFixed(2);
|
||||
if (numAmount > 0) {
|
||||
return `+$${absAmount}`;
|
||||
return `+¥${absAmount}`;
|
||||
} else if (numAmount < 0) {
|
||||
return `-$${absAmount}`;
|
||||
return `-¥${absAmount}`;
|
||||
}
|
||||
return `$${absAmount}`;
|
||||
return `¥${absAmount}`;
|
||||
};
|
||||
|
||||
// 格式化余额,只显示美元符号,不带正负号
|
||||
// 格式化余额,只显示人民币符号,不带正负号
|
||||
const formatBalance = (balance: string | number): string => {
|
||||
const numBalance = typeof balance === 'string' ? parseFloat(balance) : balance;
|
||||
if (isNaN(numBalance)) return '$0.00';
|
||||
if (isNaN(numBalance)) return '¥0.00';
|
||||
|
||||
return `$${Math.abs(numBalance).toFixed(2)}`;
|
||||
return `¥${Math.abs(numBalance).toFixed(2)}`;
|
||||
};
|
||||
|
||||
const getStatusColor = (status: number) => {
|
||||
|
||||
@@ -12,7 +12,7 @@ import { formatCurrency } from "@/shared/utils/currency";
|
||||
import DashboardOverview from "@/components/dashboard/DashboardOverview";
|
||||
import WalletManagement from "@/components/wallet/WalletManagement";
|
||||
import UserAccountBalance from "@/components/dashboard/UserAccountBalance";
|
||||
import { Home, Key, Wallet } from "lucide-react";
|
||||
import { Home, Key, Wallet, Rocket } from "lucide-react";
|
||||
import { Avatar, Card, CardBody, Button, Divider, Link } from "@nextui-org/react";
|
||||
import { RechargeModal } from "@/shared/components/modal/RechargeModal";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
@@ -92,9 +92,20 @@ const DashboardContent: React.FC = () => {
|
||||
label: "Dashboard",
|
||||
description: "Manage your integration and auth key",
|
||||
},
|
||||
{
|
||||
key: "publish-service",
|
||||
icon: <Rocket className="w-5 h-5" />,
|
||||
label: "Publish MCP Service",
|
||||
description: "Submit your own MCP service",
|
||||
},
|
||||
];
|
||||
|
||||
const handleTabNavigate = (tab: TabKey | string) => {
|
||||
// 发布 MCP 服务:跳转到独立提交页
|
||||
if (tab === "publish-service") {
|
||||
router.push("/submit");
|
||||
return;
|
||||
}
|
||||
setActiveTab(tab as TabKey);
|
||||
// update url params
|
||||
if (tab === TabKey.OVERVIEW) {
|
||||
|
||||
@@ -67,7 +67,7 @@ const DefaultDemo: React.FC = () => {
|
||||
<span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
|
||||
Beta
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">$0.02 /Per Call</span>
|
||||
<span className="text-xs text-gray-500">¥0.02 /Per Call</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -79,7 +79,7 @@ const DefaultDemo: React.FC = () => {
|
||||
<span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
|
||||
Beta
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">$0.02 /Per Call</span>
|
||||
<span className="text-xs text-gray-500">¥0.02 /Per Call</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ const TemuDemo: React.FC = () => {
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-bold text-orange-600">$9.99</span>
|
||||
<span className="text-xs font-bold text-orange-600">¥9.99</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Star className="w-2 h-2 text-yellow-400 fill-current" />
|
||||
<span className="text-xs text-gray-500">4.8</span>
|
||||
@@ -87,7 +87,7 @@ const TemuDemo: React.FC = () => {
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-bold text-orange-600">$14.99</span>
|
||||
<span className="text-xs font-bold text-orange-600">¥14.99</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Star className="w-2 h-2 text-yellow-400 fill-current" />
|
||||
<span className="text-xs text-gray-500">4.9</span>
|
||||
|
||||
@@ -46,7 +46,7 @@ export const AdminRechargeModal: React.FC<AdminRechargeModalProps> = ({
|
||||
}
|
||||
|
||||
if (numAmount < 1) {
|
||||
setError(t("Minimum recharge amount is $1"));
|
||||
setError(t("Minimum recharge amount is ¥1"));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ export const AdminRechargeModal: React.FC<AdminRechargeModalProps> = ({
|
||||
onChange={handleAmountChange}
|
||||
startContent={
|
||||
<div className="pointer-events-none flex items-center">
|
||||
<span className="text-default-400 text-small">$</span>
|
||||
<span className="text-default-400 text-small">¥</span>
|
||||
</div>
|
||||
}
|
||||
isInvalid={!!error}
|
||||
|
||||
@@ -18,7 +18,7 @@ export const useSystemConfigManagement = () => {
|
||||
const [platformConfig, setPlatformConfig] = useState<PlatformConfig>({
|
||||
name: "",
|
||||
logo: "",
|
||||
currency: "USD",
|
||||
currency: "CNY",
|
||||
});
|
||||
const [platformLoading, setPlatformLoading] = useState(false);
|
||||
const [platformError, setPlatformError] = useState<string | null>(null);
|
||||
|
||||
@@ -38,7 +38,7 @@ export const Price: React.FC<PriceProps> = ({
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-sm font-medium text-green-600">
|
||||
${priceText.toFixed(2)}
|
||||
¥{priceText.toFixed(2)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">/{t("Per Call")}</span>
|
||||
</div>
|
||||
@@ -51,14 +51,14 @@ export const Price: React.FC<PriceProps> = ({
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-gray-600">{t("Input")}:</span>
|
||||
<span className="font-medium text-green-600">
|
||||
${inputPrice.toFixed(2)}
|
||||
¥{inputPrice.toFixed(2)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">/{t("1M tokens")}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-gray-600">{t("Output")}:</span>
|
||||
<span className="font-medium text-blue-600">
|
||||
${outputPrice.toFixed(2)}
|
||||
¥{outputPrice.toFixed(2)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">/{t("1M tokens")}</span>
|
||||
</div>
|
||||
|
||||
@@ -36,7 +36,7 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
// payment channels arrive asynchronously -- fall back to the first one so the
|
||||
// confirm button is not stuck disabled on a modal opened before they load.
|
||||
const effectiveChannel = selectedPaymentChannel || paymentChannels[0]?.id || "";
|
||||
const currencySymbol = effectiveChannel === "epay" ? "¥" : "$";
|
||||
const currencySymbol = effectiveChannel === "epay" ? "¥" : "¥";
|
||||
|
||||
const channelLabel = (id: string, name: string) => {
|
||||
if (id === "epay") return t("Epay (Alipay / WeChat)");
|
||||
@@ -55,7 +55,7 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
}
|
||||
|
||||
if (numAmount < 1) {
|
||||
setError(t("Minimum recharge amount is $1"));
|
||||
setError(t("Minimum recharge amount is ¥1"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
export const _DefaultPlatformConfig: PlatformConfig = {
|
||||
name: "XPack",
|
||||
logo: "/static/logo/logo.png",
|
||||
currency: "USD",
|
||||
currency: "CNY",
|
||||
language: "en",
|
||||
website_title: "Connect Your AI Agent to the Real World - XPack",
|
||||
headline: "Connect Your AI Agent to the Real World",
|
||||
|
||||
@@ -17,7 +17,7 @@ export interface CurrencyFormatOptions {
|
||||
*/
|
||||
export const formatCurrency = (
|
||||
amount: number | undefined | null,
|
||||
currency: string = 'USD',
|
||||
currency: string = 'CNY',
|
||||
options: CurrencyFormatOptions = {}
|
||||
): string => {
|
||||
// 处理无效值
|
||||
@@ -33,7 +33,7 @@ export const formatCurrency = (
|
||||
|
||||
try {
|
||||
if (showSymbol) {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
return new Intl.NumberFormat('zh-CN', {
|
||||
style: 'currency',
|
||||
currency: currency,
|
||||
minimumFractionDigits,
|
||||
@@ -64,7 +64,7 @@ export const formatCurrency = (
|
||||
*/
|
||||
export const formatPrice = (
|
||||
priceInCents: number | undefined | null,
|
||||
currency: string = 'USD',
|
||||
currency: string = 'CNY',
|
||||
options: CurrencyFormatOptions = {}
|
||||
): string => {
|
||||
if (priceInCents === undefined || priceInCents === null || isNaN(priceInCents)) {
|
||||
@@ -80,9 +80,9 @@ export const formatPrice = (
|
||||
* @param currency 货币代码
|
||||
* @returns 货币符号
|
||||
*/
|
||||
export const getCurrencySymbol = (currency: string = 'USD'): string => {
|
||||
export const getCurrencySymbol = (currency: string = 'CNY'): string => {
|
||||
try {
|
||||
const formatter = new Intl.NumberFormat('en-US', {
|
||||
const formatter = new Intl.NumberFormat('zh-CN', {
|
||||
style: 'currency',
|
||||
currency: currency,
|
||||
minimumFractionDigits: 0,
|
||||
@@ -114,7 +114,7 @@ export const getCurrencySymbol = (currency: string = 'USD'): string => {
|
||||
*/
|
||||
export const formatBalance = (
|
||||
balance: number | undefined | null,
|
||||
currency: string = 'USD'
|
||||
currency: string = 'CNY'
|
||||
): string => {
|
||||
return formatCurrency(balance, currency, {
|
||||
minimumFractionDigits: 2,
|
||||
|
||||
@@ -3,6 +3,12 @@
|
||||
# Description: Dockerfile for XPack
|
||||
FROM python:3.12.11-alpine3.22
|
||||
|
||||
# Build-time proxy (needed for apk/pip in restricted networks)
|
||||
ARG HTTP_PROXY
|
||||
ARG HTTPS_PROXY
|
||||
ARG NO_PROXY
|
||||
ENV HTTP_PROXY=$HTTP_PROXY HTTPS_PROXY=$HTTPS_PROXY NO_PROXY=$NO_PROXY
|
||||
|
||||
RUN apk add nodejs=~22 npm uv nginx
|
||||
# ENV TZ=Asia/Shanghai
|
||||
# RUN ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \
|
||||
@@ -16,6 +22,8 @@ RUN mkdir -p /$APP
|
||||
WORKDIR /$APP
|
||||
COPY requirements.txt /$APP/requirements.txt
|
||||
|
||||
# 国内 PyPI 镜像源(避免走代理直连 PyPI 过慢)
|
||||
ENV UV_DEFAULT_INDEX=https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
RUN uv venv && source .venv/bin/activate && uv pip install -r requirements.txt
|
||||
RUN echo $VERSION > .version
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""User submission controller for MCP/Skill/Plugin marketplace."""
|
||||
"""User submission controller for MCP marketplace."""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -141,7 +141,7 @@ def _publish_mcp_service(db: Session, sub: Submission) -> str:
|
||||
return service.id
|
||||
|
||||
|
||||
@router.post("/submission", summary="User submit MCP/Skill/Plugin")
|
||||
@router.post("/submission", summary="User submit MCP")
|
||||
async def create_submission(
|
||||
request: Request,
|
||||
type: str = Form(...),
|
||||
@@ -163,7 +163,7 @@ async def create_submission(
|
||||
if not user_id:
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
if type not in ("mcp", "skill", "plugin"):
|
||||
if type != "mcp":
|
||||
return ResponseUtils.error(error_msg=error_msg.INVALID_PARAMETER)
|
||||
|
||||
# MCP submissions must declare where the service lives so that approving
|
||||
|
||||
@@ -270,7 +270,7 @@ class McpService:
|
||||
"""
|
||||
return self.service_repository.get_by_id(service_id, force_update)
|
||||
def get_service_call_params(self, service_id: str) -> dict:
|
||||
service = self.service_repository.get_by_id(service_id, force_update=False)
|
||||
service = self.service_repository.get_by_id(service_id, force_update=True)
|
||||
if not service:
|
||||
return {}
|
||||
headers = {}
|
||||
@@ -278,9 +278,18 @@ class McpService:
|
||||
for item in json.loads(service.headers):
|
||||
if "name" in item and "value" in item:
|
||||
headers[item["name"]] = item["value"]
|
||||
# Apply the service's own auth credential (e.g. upstream Bearer token)
|
||||
if getattr(service, "auth_token", None):
|
||||
token = str(service.auth_token).strip()
|
||||
method = (service.auth_method or "").lower()
|
||||
if method in ("bearer", "token", "api_key", "apikey") and not token.lower().startswith(("bearer ", "token ")):
|
||||
token = f"Bearer {token}"
|
||||
headers[service.auth_header or "Authorization"] = token
|
||||
return {
|
||||
"base_url": service.base_url or "",
|
||||
"headers": headers
|
||||
"headers": headers,
|
||||
"service_type": service.service_type or "",
|
||||
"service_id": service.id,
|
||||
}
|
||||
|
||||
def _build_output_schema(self,tool_api:McpToolApi) -> Optional[dict]:
|
||||
|
||||
@@ -16,6 +16,8 @@ class McpToolService:
|
||||
|
||||
def __init__(self):
|
||||
self.http_builder = HttpRequestBuilder()
|
||||
# base_url -> MCP session id, reused across calls of the same upstream
|
||||
self._mcp_sessions: Dict[str, str] = {}
|
||||
|
||||
async def execute_tool(self, tool_config, arguments: dict, call_params: dict) -> tuple[List[types.Content],dict,bool]:
|
||||
"""
|
||||
@@ -31,7 +33,11 @@ class McpToolService:
|
||||
"""
|
||||
try:
|
||||
logger.info(f"Starting tool execution: {tool_config.name}")
|
||||
|
||||
|
||||
# Upstream is a native MCP server (JSON-RPC over streamable HTTP)
|
||||
if (call_params or {}).get("service_type") == "mcp":
|
||||
return await self._execute_mcp_upstream(tool_config, arguments, call_params)
|
||||
|
||||
# Build HTTP request
|
||||
request_info = self.http_builder.build_request(tool_config, arguments, call_params)
|
||||
|
||||
@@ -49,6 +55,126 @@ class McpToolService:
|
||||
logger.error(f"Tool execution failed: {error_msg}", exc_info=True)
|
||||
return [types.TextContent(type="text", text=error_msg)],{},False
|
||||
|
||||
def _parse_jsonrpc_body(self, text: str) -> Any:
|
||||
"""Parse a JSON-RPC reply that may arrive as plain JSON or SSE frames."""
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
if text.startswith("{") or text.startswith("["):
|
||||
try:
|
||||
return json.loads(text)
|
||||
except Exception:
|
||||
pass
|
||||
parsed = None
|
||||
for chunk in text.split("\n\n"):
|
||||
for line in chunk.splitlines():
|
||||
line = line.strip()
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
payload = line[5:].strip()
|
||||
if not payload or payload == "[DONE]":
|
||||
continue
|
||||
try:
|
||||
parsed = json.loads(payload)
|
||||
except Exception:
|
||||
continue
|
||||
return parsed
|
||||
|
||||
async def _execute_mcp_upstream(self, tool_config, arguments: dict, call_params: dict):
|
||||
"""Forward a tool call to an upstream native MCP server (streamable HTTP)."""
|
||||
base_url = (call_params.get("base_url") or "").strip().rstrip("/")
|
||||
if not base_url:
|
||||
raise RuntimeError("MCP service base_url is empty")
|
||||
|
||||
tool_name = (getattr(tool_config, "path", None) or tool_config.name or "").strip()
|
||||
if tool_name.startswith("mcp:"):
|
||||
tool_name = tool_name[4:]
|
||||
if not tool_name:
|
||||
raise RuntimeError("MCP tool name is empty")
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, text/event-stream",
|
||||
}
|
||||
headers.update(call_params.get("headers") or {})
|
||||
|
||||
logger.info(f"Forwarding MCP tool call to upstream: {base_url} -> {tool_name}")
|
||||
|
||||
call_request = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": 2,
|
||||
"method": "tools/call",
|
||||
"params": {"name": tool_name, "arguments": arguments or {}},
|
||||
}
|
||||
|
||||
async with create_mcp_http_client(headers=headers) as client:
|
||||
session_id = self._mcp_sessions.get(base_url)
|
||||
call_headers = dict(headers)
|
||||
if session_id:
|
||||
call_headers["Mcp-Session-Id"] = session_id
|
||||
|
||||
response = await client.post(base_url, json=call_request, headers=call_headers)
|
||||
raw_text = response.text or ""
|
||||
payload = self._parse_jsonrpc_body(raw_text)
|
||||
|
||||
# Stateless servers answer immediately; stateful ones need a handshake first.
|
||||
if not (isinstance(payload, dict) and "result" in payload):
|
||||
handshake = await self._mcp_handshake(client, base_url, headers)
|
||||
if handshake:
|
||||
session_id = handshake
|
||||
self._mcp_sessions[base_url] = session_id
|
||||
call_headers = dict(headers)
|
||||
call_headers["Mcp-Session-Id"] = session_id
|
||||
response = await client.post(base_url, json=call_request, headers=call_headers)
|
||||
raw_text = response.text or ""
|
||||
payload = self._parse_jsonrpc_body(raw_text)
|
||||
|
||||
if payload is None:
|
||||
if response.status_code >= 400:
|
||||
raise RuntimeError(f"Upstream MCP HTTP {response.status_code}: {raw_text[:500]}")
|
||||
raise RuntimeError(f"Invalid JSON-RPC response from upstream MCP: {raw_text[:500]}")
|
||||
|
||||
if isinstance(payload, dict) and payload.get("error"):
|
||||
raise RuntimeError(f"Upstream MCP error: {json.dumps(payload['error'], ensure_ascii=False)}")
|
||||
|
||||
result = payload.get("result") if isinstance(payload, dict) else payload
|
||||
text_out = json.dumps(result, ensure_ascii=False, default=str)
|
||||
logger.info("Upstream MCP tool execution completed")
|
||||
return [types.TextContent(type="text", text=text_out)], (result or {}), True
|
||||
|
||||
async def _mcp_handshake(self, client, base_url: str, headers: dict) -> str:
|
||||
"""Run initialize (+initialized notification) and return the MCP session id."""
|
||||
try:
|
||||
init_request = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": "2025-06-18",
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "xpack-mcp-market", "version": "1.5.2"},
|
||||
},
|
||||
}
|
||||
init_response = await client.post(base_url, json=init_request)
|
||||
session_id = init_response.headers.get("mcp-session-id") or init_response.headers.get(
|
||||
"Mcp-Session-Id"
|
||||
)
|
||||
if session_id:
|
||||
notify_headers = dict(headers)
|
||||
notify_headers["Mcp-Session-Id"] = session_id
|
||||
try:
|
||||
await client.post(
|
||||
base_url,
|
||||
json={"jsonrpc": "2.0", "method": "notifications/initialized"},
|
||||
headers=notify_headers,
|
||||
)
|
||||
except Exception as notify_error: # some servers reject notifications
|
||||
logger.debug(f"Upstream MCP initialized notification ignored: {notify_error}")
|
||||
return session_id or ""
|
||||
except Exception as handshake_error:
|
||||
logger.warning(f"Upstream MCP handshake skipped: {handshake_error}")
|
||||
return ""
|
||||
|
||||
async def _send_http_request(self, request_info: Dict[str, Any]) -> str:
|
||||
"""
|
||||
Send HTTP request
|
||||
|
||||
@@ -63,6 +63,9 @@ class Config:
|
||||
"/api/web/mcp_services",
|
||||
"/api/web/mcp_service_info",
|
||||
"/api/payment/callback_stripe",
|
||||
# epay (易支付) async notify — called by the gateway, no user token.
|
||||
"/api/payment/callback_epay",
|
||||
"/api/payment/refund_callback_epay",
|
||||
# "/api/payment/callback_alipay",
|
||||
]
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""User submission model for MCP/Skill/Plugin marketplace."""
|
||||
"""User submission model for MCP marketplace."""
|
||||
from sqlalchemy import Column, String, Text, DateTime, JSON, Enum
|
||||
from sqlalchemy.sql import func
|
||||
from services.common.models.base import Base
|
||||
|
||||
Reference in new issue
Block a user