Compare commits

...
5 Commits
Author SHA1 Message Date
jinghui 4b373d143f feat(mcp): 原生 MCP 上游转发(streamable HTTP JSON-RPC 透传)
release / release (release) Waiting to run
- service_type=mcp 分支:tools/call 直接转发上游 MCP 服务,解析纯 JSON 与 SSE 双格式
- 复用 Mcp-Session-Id 会话,按 base_url 缓存
- 调用参数带上游 auth_token(Bearer 自动补前缀)
- get_service_call_params 强制刷新,配置改动立即生效
2026-11-23 18:50:27 +08:00
jinghui 8529ac2e60 docs: 更新部署镜像 tag 至 v1.5.1 2026-11-14 01:01:10 +08:00
jinghui 7f47841fdc feat(submission): 移除技能/插件提交入口,仅保留 MCP 服务
release / release (release) Canceled after 0s
2026-11-14 00:54:47 +08:00
jinghui f5b45af30a docs: README 增加国内镜像部署章节(docker run + docker-compose 两种方式)
release / release (release) Canceled after 0s
2026-11-13 22:07:52 +08:00
jinghui 851d45a573 feat(console): 用户中心新增发布 MCP 服务入口与我的提交记录
- 侧边栏新增「发布 MCP 服务」入口(Rocket 图标)跳转 /submit,补 zh-CN 翻译键
- /submit 新增「我的提交记录」:登录后展示自己的提交列表(类型/时间/状态徽章/审核备注),提交成功自动刷新
- 修复登录判断:改读 zustand store 的 user_token(原读 localStorage['user_token'],
  网页登录只写 zustand 不写该键,导致所有网页用户提交时误报「请先登录后再提交」)
- 列表加载改为按接口返回判定登录态(token 失效自动清空记录)
2026-11-13 22:07:50 +08:00
9 changed files with 309 additions and 24 deletions

No files matched your search

+43
View File
@@ -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. - [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 - [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
```
@@ -968,5 +968,12 @@
"Example 100": "如 100", "Example 100": "如 100",
"Enter a non-negative integer": "请输入非负整数", "Enter a non-negative integer": "请输入非负整数",
"Free call limit saved": "免费调用上限已保存", "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": "已拒绝"
} }
+102 -15
View File
@@ -1,11 +1,34 @@
"use client"; "use client";
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
import { fetchAPI } from "@/shared/rpc/common-function"; 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() { 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 [name, setName] = useState("");
const [desc, setDesc] = useState(""); const [desc, setDesc] = useState("");
const [file, setFile] = useState<File | null>(null); const [file, setFile] = useState<File | null>(null);
@@ -17,12 +40,38 @@ export default function SubmitPage() {
const [freeDailyLimit, setFreeDailyLimit] = useState(""); const [freeDailyLimit, setFreeDailyLimit] = useState("");
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null); const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [submitting, setSubmitting] = useState(false); 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) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
setMsg(null); setMsg(null);
if (typeof window !== "undefined" && !localStorage.getItem("user_token")) { if (typeof window !== "undefined" && !user_token) {
setMsg({ ok: false, text: "请先登录后再提交(右上角登录)" }); setMsg({ ok: false, text: "请先登录后再提交(右上角登录)" });
return; return;
} }
@@ -54,6 +103,7 @@ export default function SubmitPage() {
if (data?.success) { if (data?.success) {
setMsg({ ok: true, text: "提交成功,等待管理员审核。审核通过后将自动上架到市场。" }); setMsg({ ok: true, text: "提交成功,等待管理员审核。审核通过后将自动上架到市场。" });
setName(""); setDesc(""); setFile(null); setBaseUrl(""); setTags(""); setName(""); setDesc(""); setFile(null); setBaseUrl(""); setTags("");
loadSubs();
} else { } else {
setMsg({ ok: false, text: data?.error_message || "提交失败,请稍后重试" }); setMsg({ ok: false, text: data?.error_message || "提交失败,请稍后重试" });
} }
@@ -69,16 +119,10 @@ export default function SubmitPage() {
return ( return (
<div className="max-w-xl mx-auto p-6"> <div className="max-w-xl mx-auto p-6">
<div className="flex items-center justify-between mb-4"> <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> </div>
<form onSubmit={handleSubmit} className="space-y-4"> <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 /> <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} /> <textarea value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="描述" className={inputCls} rows={3} />
@@ -150,10 +194,6 @@ export default function SubmitPage() {
</div> </div>
)} )}
{type !== "mcp" && (
<input type="file" onChange={(e) => setFile(e.target.files?.[0] || null)} className={inputCls} />
)}
<button <button
type="submit" type="submit"
disabled={submitting} disabled={submitting}
@@ -168,6 +208,53 @@ export default function SubmitPage() {
{msg.text} {msg.text}
</pre> </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> </div>
); );
} }
+12 -1
View File
@@ -12,7 +12,7 @@ import { formatCurrency } from "@/shared/utils/currency";
import DashboardOverview from "@/components/dashboard/DashboardOverview"; import DashboardOverview from "@/components/dashboard/DashboardOverview";
import WalletManagement from "@/components/wallet/WalletManagement"; import WalletManagement from "@/components/wallet/WalletManagement";
import UserAccountBalance from "@/components/dashboard/UserAccountBalance"; 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 { Avatar, Card, CardBody, Button, Divider, Link } from "@nextui-org/react";
import { RechargeModal } from "@/shared/components/modal/RechargeModal"; import { RechargeModal } from "@/shared/components/modal/RechargeModal";
import { useTranslation } from "@/shared/lib/useTranslation"; import { useTranslation } from "@/shared/lib/useTranslation";
@@ -92,9 +92,20 @@ const DashboardContent: React.FC = () => {
label: "Dashboard", label: "Dashboard",
description: "Manage your integration and auth key", 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) => { const handleTabNavigate = (tab: TabKey | string) => {
// 发布 MCP 服务:跳转到独立提交页
if (tab === "publish-service") {
router.push("/submit");
return;
}
setActiveTab(tab as TabKey); setActiveTab(tab as TabKey);
// update url params // update url params
if (tab === TabKey.OVERVIEW) { if (tab === TabKey.OVERVIEW) {
+2
View File
@@ -22,6 +22,8 @@ RUN mkdir -p /$APP
WORKDIR /$APP WORKDIR /$APP
COPY requirements.txt /$APP/requirements.txt 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 uv venv && source .venv/bin/activate && uv pip install -r requirements.txt
RUN echo $VERSION > .version 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 json
import logging import logging
import os import os
@@ -141,7 +141,7 @@ def _publish_mcp_service(db: Session, sub: Submission) -> str:
return service.id return service.id
@router.post("/submission", summary="User submit MCP/Skill/Plugin") @router.post("/submission", summary="User submit MCP")
async def create_submission( async def create_submission(
request: Request, request: Request,
type: str = Form(...), type: str = Form(...),
@@ -163,7 +163,7 @@ async def create_submission(
if not user_id: if not user_id:
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION) 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) return ResponseUtils.error(error_msg=error_msg.INVALID_PARAMETER)
# MCP submissions must declare where the service lives so that approving # MCP submissions must declare where the service lives so that approving
+11 -2
View File
@@ -270,7 +270,7 @@ class McpService:
""" """
return self.service_repository.get_by_id(service_id, force_update) return self.service_repository.get_by_id(service_id, force_update)
def get_service_call_params(self, service_id: str) -> dict: 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: if not service:
return {} return {}
headers = {} headers = {}
@@ -278,9 +278,18 @@ class McpService:
for item in json.loads(service.headers): for item in json.loads(service.headers):
if "name" in item and "value" in item: if "name" in item and "value" in item:
headers[item["name"]] = item["value"] 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 { return {
"base_url": service.base_url or "", "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]: def _build_output_schema(self,tool_api:McpToolApi) -> Optional[dict]:
@@ -16,6 +16,8 @@ class McpToolService:
def __init__(self): def __init__(self):
self.http_builder = HttpRequestBuilder() 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]: 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: try:
logger.info(f"Starting tool execution: {tool_config.name}") 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 # Build HTTP request
request_info = self.http_builder.build_request(tool_config, arguments, call_params) 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) logger.error(f"Tool execution failed: {error_msg}", exc_info=True)
return [types.TextContent(type="text", text=error_msg)],{},False 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: async def _send_http_request(self, request_info: Dict[str, Any]) -> str:
""" """
Send HTTP request Send HTTP request
+1 -1
View File
@@ -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 import Column, String, Text, DateTime, JSON, Enum
from sqlalchemy.sql import func from sqlalchemy.sql import func
from services.common.models.base import Base from services.common.models.base import Base