Compare commits

...
2 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
3 changed files with 142 additions and 7 deletions

No files matched your search

+4 -4
View File
@@ -350,8 +350,8 @@ For details, please see the [LICENSE](./LICENSE) file.
镜像已双渠道发布,任选其一拉取:
- 公网:`gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.0`、`jpccr.ccs.tencentyun.com/jinghui/xpack-mcp-market:v1.5.0`
- 内网:`192.168.68.19:3200/jinghui/xpack-mcp-market:v1.5.0`
- 公网:`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(推荐,带齐全部服务参数)
@@ -360,7 +360,7 @@ 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.0
# → image: gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.1
# 2) 准备环境变量(支付渠道加密密钥,必须改掉示例值)
cp .env.example .env && vim .env # 修改 PAYMENT_CONFIG_SECRET_KEY 为自己的 32 字节随机串
@@ -384,5 +384,5 @@ docker run -d --name xpack-mcp-market \
-e PAYMENT_CONFIG_SECRET_KEY='<32字节随机串>' \
-e PAYMENT_CONFIG_KEY_ID=default \
--network <依赖服务所在网络> \
gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.0
gitea.88531.cn/jinghui/xpack-mcp-market:v1.5.1
```
+11 -2
View File
@@ -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