Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(mcp-server): route diagnostics to stderr to fix stdio protocol crash (#2371)
annopick400bbbf71769
diff --git a/.github/workflows/mcp-server.yml b/.github/workflows/mcp-server.ymlnew file mode 100644index 000000000..1be2f076f--- /dev/null+++ b/.github/workflows/mcp-server.yml@@ -0,0 +1,106 @@+name: Build & Publish (mcp-server)++# Build, test, and publish the Python MCP server (mcp-server/) to PyPI.+# Publishing uses PyPI Trusted Publishing (OIDC) — no API token required,+# only the GitHub→PyPI OIDC trust configured on the repo.+#+# Release tags: mcp-server-v* (e.g. mcp-server-v1.0.1)++on:+ push:+ branches: [main]+ tags:+ - "mcp-server-v*"+ paths:+ - "mcp-server/**"+ - ".github/workflows/mcp-server.yml"+ pull_request:+ paths:+ - "mcp-server/**"+ - ".github/workflows/mcp-server.yml"+ workflow_dispatch:++permissions:+ contents: read++jobs:+ test:+ name: Test (Python ${{ matrix.python-version }})+ runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.10", "3.11", "3.12", "3.13"]+ defaults:+ run:+ working-directory: mcp-server+ steps:+ - uses: actions/checkout@v4++ - name: Install uv+ uses: astral-sh/setup-uv@v4++ - name: Set up Python ${{ matrix.python-version }}+ run: uv python install ${{ matrix.python-version }}++ - name: Install dependencies (test extras)+ run: uv sync --python ${{ matrix.python-version }} --extra test++ - name: Run tests+ # unittest avoids pytest importing __init__.py as a broken package root.+ run: uv run --python ${{ matrix.python-version }} python -m unittest discover -s . -p "test_*.py" -v++ build:+ name: Build sdist + wheel+ needs: test+ runs-on: ubuntu-latest+ if: startsWith(github.ref, 'refs/tags/mcp-server-v')+ defaults:+ run:+ working-directory: mcp-server+ steps:+ - uses: actions/checkout@v4++ - name: Install uv+ uses: astral-sh/setup-uv@v4++ - name: Set up Python+ run: uv python install 3.12++ - name: Build package+ run: uv build++ - name: Verify wheel contains upload_paths.py (regression guard)+ run: |+ set -e+ if ! python3 -c "import glob, zipfile, sys; whl=glob.glob('dist/*.whl')[0]; z=zipfile.ZipFile(whl); sys.exit(0 if 'upload_paths.py' in z.namelist() else 1)"; then+ echo "::error::upload_paths.py is missing from the wheel — check py-modules in pyproject.toml/setup.py"+ exit 1+ fi+ echo "upload_paths.py present in wheel ✓"++ - name: Upload artifacts+ uses: actions/upload-artifact@v4+ with:+ name: dist+ path: mcp-server/dist/++ publish:+ name: Publish to PyPI+ needs: build+ runs-on: ubuntu-latest+ if: startsWith(github.ref, 'refs/tags/mcp-server-v')+ permissions:+ id-token: write+ environment:+ name: pypi+ url: https://pypi.org/project/weknora-mcp/+ steps:+ - name: Download artifacts+ uses: actions/download-artifact@v4+ with:+ name: dist+ path: dist/++ - name: Publish to PyPI+ uses: pypa/gh-action-pypi-publish@release/v1diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.ymlnew file mode 100644index 000000000..8d2149201--- /dev/null+++ b/.github/workflows/workflow.yml@@ -0,0 +1,115 @@+name: Build & Publish (mcp-server)++# Build, test, and publish the Python MCP server (mcp-server/) to PyPI.+# Publishing uses PyPI Trusted Publishing (OIDC) — no API token required,+# only the GitHub→PyPI OIDC trust configured on the repo.+#+# Adapted from annopick/tuomin .github/workflows/ci.yml, adjusted for the+# mcp-server/ subdirectory layout and its flat test_*.py test files.++on:+ push:+ branches: [main]+ tags:+ - "mcp-server-v*"+ paths:+ - "mcp-server/**"+ - ".github/workflows/workflow.yml"+ pull_request:+ paths:+ - "mcp-server/**"+ - ".github/workflows/workflow.yml"+ workflow_dispatch:++# Default: read-only. The publish job overrides with id-token: write.+permissions:+ contents: read++jobs:+ test:+ name: Test (Python ${{ matrix.python-version }})+ runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ # requires-python = ">=3.10" in mcp-server/pyproject.toml+ python-version: ["3.10", "3.11", "3.12", "3.13"]+ defaults:+ run:+ working-directory: mcp-server+ steps:+ - uses: actions/checkout@v4++ - name: Install uv+ uses: astral-sh/setup-uv@v4++ - name: Set up Python ${{ matrix.python-version }}+ run: uv python install ${{ matrix.python-version }}++ - name: Install dependencies (test extras)+ run: uv sync --python ${{ matrix.python-version }} --extra test++ - name: Run tests+ # mcp-server has no tests/ dir; tests are flat test_*.py files.+ # Point pytest at them explicitly (pyproject testpaths points at a+ # nonexistent tests/ dir, so --override-ini keeps it working).+ run: uv run --python ${{ matrix.python-version }} pytest test_*.py -v --override-ini "testpaths=."++ build:+ name: Build sdist + wheel+ needs: test+ runs-on: ubuntu-latest+ # Only build release artifacts on tagged releases; PR/push-to-main just test.+ if: startsWith(github.ref, 'refs/tags/mcp-server-v')+ defaults:+ run:+ working-directory: mcp-server+ steps:+ - uses: actions/checkout@v4++ - name: Install uv+ uses: astral-sh/setup-uv@v4++ - name: Set up Python+ run: uv python install 3.12++ - name: Build package+ run: uv build++ - name: Verify wheel contains upload_paths.py (regression guard)+ # Guards against the 1.0.0 bug where upload_paths.py was dropped+ # from the wheel because it was missing from py-modules.+ run: |+ set -e+ if ! python -c "import glob, zipfile, sys; whl=glob.glob('dist/*.whl')[0]; z=zipfile.ZipFile(whl); sys.exit(0 if 'upload_paths.py' in z.namelist() else 1)"; then+ echo "::error::upload_paths.py is missing from the wheel — check py-modules in pyproject.toml/setup.py"+ exit 1+ fi+ echo "upload_paths.py present in wheel ✓"++ - name: Upload artifacts+ uses: actions/upload-artifact@v4+ with:+ name: dist+ path: mcp-server/dist/++ publish:+ name: Publish to PyPI+ needs: build+ runs-on: ubuntu-latest+ if: startsWith(github.ref, 'refs/tags/mcp-server-v')+ # Required for PyPI Trusted Publishing (OIDC).+ permissions:+ id-token: write+ environment:+ name: pypi+ url: https://pypi.org/project/weknora-mcp/+ steps:+ - name: Download artifacts+ uses: actions/download-artifact@v4+ with:+ name: dist+ path: dist/++ - name: Publish to PyPI+ uses: pypa/gh-action-pypi-publish@release/v1diff --git a/mcp-server/CHANGELOG.md b/mcp-server/CHANGELOG.mdindex e4736a459..9cb2ccaae 100644--- a/mcp-server/CHANGELOG.md+++ b/mcp-server/CHANGELOG.md@@ -5,6 +5,17 @@格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.0.0/),并且本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。+## [1.0.1] - 2026-07-28++### 修复+- 将入口脚本(`run_server.py`、`main.py`、`run.py`)的诊断输出改到 stderr,避免破坏 MCP stdio 协议流导致客户端启动失败+- 修复 wheel 漏打包 `upload_paths.py` 导致的 `ModuleNotFoundError`+- 将 `__init__.py` 改为绝对导入,修复 unittest/pytest 收集测试时的包导入错误++### 变更+- PyPI 分发包名统一为 `weknora-mcp`(命令行入口 `weknora-mcp-server` / `weknora-server` 不变)+- 新增 CI workflow(`.github/workflows/mcp-server.yml`),发布 tag 格式为 `mcp-server-v*`+## [1.0.0] - 2024-01-XX### 新增diff --git a/mcp-server/MCP_CONFIG.md b/mcp-server/MCP_CONFIG.mdindex 8c095a29b..6657e392b 100644--- a/mcp-server/MCP_CONFIG.md+++ b/mcp-server/MCP_CONFIG.md@@ -1,6 +1,8 @@# 使用 uv 运行 WeKnora MCP 服务器> 更推荐使用`uv`来运行基于python的MCP服务。+>+> 也可通过 PyPI 安装:`pip install weknora-mcp`(包名 `weknora-mcp`,非 `weknora-mcp-server`)。## 1. 安装 uvdiff --git a/mcp-server/README.md b/mcp-server/README.mdindex 208c59e98..b296ccbdd 100644--- a/mcp-server/README.md+++ b/mcp-server/README.md@@ -58,6 +58,15 @@ python main.py --version # 显示版本信息## 安装为 Python 包+### 从 PyPI 安装++```bash+pip install weknora-mcp+```++> PyPI 包名为 **`weknora-mcp`**(请勿与第三方包 `weknora-mcp-server` 混淆)。+> 安装后命令行入口仍为 `weknora-mcp-server` / `weknora-server`。+### 开发模式安装```bashpip install -e .diff --git a/mcp-server/__init__.py b/mcp-server/__init__.pyindex 3a574e121..9ae556f8e 100644--- a/mcp-server/__init__.py+++ b/mcp-server/__init__.py@@ -5,10 +5,10 @@ WeKnora MCP Server PackageA Model Context Protocol server that provides access to the WeKnora knowledge management API."""-__version__ = "1.0.0"+__version__ = "1.0.1"__author__ = "WeKnora Team"__description__ = "WeKnora MCP Server - Model Context Protocol server for WeKnora API"-from .weknora_mcp_server import WeKnoraClient, run+from weknora_mcp_server import WeKnoraClient, run__all__ = ["WeKnoraClient", "run"]diff --git a/mcp-server/main.py b/mcp-server/main.pyindex 4572ed180..cd77b5da2 100644--- a/mcp-server/main.py+++ b/mcp-server/main.py@@ -7,6 +7,10 @@ WeKnora MCP Server 主入口点1. python main.py2. python -m weknora_mcp_server3. weknora-mcp-server (安装后)++注意:在 stdio 传输下,stdout 是 JSON-RPC 通道,所有诊断/提示信息必须写入+stderr,否则会破坏 MCP 协议流导致客户端判定"启动失败"。本文件所有 print+均通过 stderr 输出。"""import argparse@@ -32,8 +36,8 @@ def check_dependencies():return Trueexcept ImportError as e:- print(f"缺少依赖: {e}")- print("请运行: pip install -r requirements.txt")+ print(f"缺少依赖: {e}", file=sys.stderr)+ print("请运行: pip install -r requirements.txt", file=sys.stderr)return False@@ -42,17 +46,17 @@ def check_environment_variables():base_url = os.getenv("WEKNORA_BASE_URL")api_key = os.getenv("WEKNORA_API_KEY")- print("=== WeKnora MCP Server 环境检查 ===")- print(f"Base URL: {base_url or 'http://localhost:8080/api/v1 (默认)'}")- print(f"API Key: {'已设置' if api_key else '未设置 (警告)'}")+ print("=== WeKnora MCP Server 环境检查 ===", file=sys.stderr)+ print(f"Base URL: {base_url or 'http://localhost:8080/api/v1 (默认)'}", file=sys.stderr)+ print(f"API Key: {'已设置' if api_key else '未设置 (警告)'}", file=sys.stderr)if not base_url:- print("提示: 可以设置 WEKNORA_BASE_URL 环境变量")+ print("提示: 可以设置 WEKNORA_BASE_URL 环境变量", file=sys.stderr)if not api_key:- print("警告: 建议设置 WEKNORA_API_KEY 环境变量")+ print("警告: 建议设置 WEKNORA_API_KEY 环境变量", file=sys.stderr)- print("=" * 40)+ print("=" * 40, file=sys.stderr)return True@@ -81,7 +85,7 @@ def parse_arguments():parser.add_argument("--verbose", "-v", action="store_true", help="启用详细日志输出")parser.add_argument(- "--version", action="version", version="WeKnora MCP Server 1.0.0"+ "--version", action="version", version="WeKnora MCP Server 1.0.1")parser.add_argument(@@ -121,7 +125,7 @@ async def main():# 如果只是检查环境,则退出if args.check_only:- print("环境检查完成。")+ print("环境检查完成。", file=sys.stderr)return# 设置日志级别@@ -129,10 +133,10 @@ async def main():import logginglogging.basicConfig(level=logging.DEBUG)- print("已启用详细日志模式")+ print("已启用详细日志模式", file=sys.stderr)try:- print(f"正在启动 WeKnora MCP Server (transport={args.transport})...")+ print(f"正在启动 WeKnora MCP Server (transport={args.transport})...", file=sys.stderr)from weknora_mcp_server import run_stdio, run_sse, run_http@@ -151,13 +155,13 @@ async def main():await run_http(args.host, args.port)except ImportError as e:- print(f"导入错误: {e}")- print("请确保所有文件都在正确的位置")+ print(f"导入错误: {e}", file=sys.stderr)+ print("请确保所有文件都在正确的位置", file=sys.stderr)sys.exit(1)except KeyboardInterrupt:- print("\n服务器已停止")+ print("\n服务器已停止", file=sys.stderr)except Exception as e:- print(f"服务器运行错误: {e}")+ print(f"服务器运行错误: {e}", file=sys.stderr)if args.verbose:import tracebackdiff --git a/mcp-server/pyproject.toml b/mcp-server/pyproject.tomlindex f4d122000..597e6d60e 100644--- a/mcp-server/pyproject.toml+++ b/mcp-server/pyproject.toml@@ -3,8 +3,8 @@ requires = ["setuptools>=45", "wheel", "setuptools_scm[toml]>=6.2"]build-backend = "setuptools.build_meta"[project]-name = "weknora-mcp-server"-version = "1.0.0"+name = "weknora-mcp"+version = "1.0.1"description = "WeKnora MCP Server - Model Context Protocol server for WeKnora API"readme = "README.md"license = {text = "MIT"}@@ -60,7 +60,7 @@ weknora-mcp-server = "main:sync_main"weknora-server = "run_server:main"[tool.setuptools]-py-modules = ["weknora_mcp_server", "main", "run_server", "run", "test_module"]+py-modules = ["weknora_mcp_server", "upload_paths", "main", "run_server", "run", "test_module"]include-package-data = true[tool.setuptools.package-data]diff --git a/mcp-server/run.py b/mcp-server/run.pyindex 02c6f6229..1d23e7b1c 100644--- a/mcp-server/run.py+++ b/mcp-server/run.py@@ -4,6 +4,10 @@ WeKnora MCP Server 便捷启动脚本这是一个简化的启动脚本,提供最基本的功能。对于更多选项,请使用 main.py++注意:在 stdio 传输下,stdout 是 JSON-RPC 通道,所有诊断/提示信息必须写入+stderr,否则会破坏 MCP 协议流导致客户端判定"启动失败"。本脚本所有 print+均通过 stderr 输出。"""import os@@ -22,10 +26,10 @@ def main():base_url = os.getenv("WEKNORA_BASE_URL", "http://localhost:8080/api/v1")api_key = os.getenv("WEKNORA_API_KEY", "")- print("WeKnora MCP Server")- print(f"Base URL: {base_url}")- print(f"API Key: {'已设置' if api_key else '未设置'}")- print("-" * 40)+ print("WeKnora MCP Server", file=sys.stderr)+ print(f"Base URL: {base_url}", file=sys.stderr)+ print(f"API Key: {'已设置' if api_key else '未设置'}", file=sys.stderr)+ print("-" * 40, file=sys.stderr)try:# 导入并运行@@ -33,13 +37,13 @@ def main():sync_main()except ImportError:- print("错误: 无法导入必要模块")- print("请确保运行: pip install -r requirements.txt")+ print("错误: 无法导入必要模块", file=sys.stderr)+ print("请确保运行: pip install -r requirements.txt", file=sys.stderr)sys.exit(1)except KeyboardInterrupt:- print("\n服务器已停止")+ print("\n服务器已停止", file=sys.stderr)except Exception as e:- print(f"错误: {e}")+ print(f"错误: {e}", file=sys.stderr)sys.exit(1)diff --git a/mcp-server/run_server.py b/mcp-server/run_server.pyindex fc1226556..518f2aa1d 100644--- a/mcp-server/run_server.py+++ b/mcp-server/run_server.py@@ -1,6 +1,10 @@#!/usr/bin/env python3"""WeKnora MCP Server 启动脚本++注意:在 stdio 传输下,stdout 是 JSON-RPC 通道,所有诊断/提示信息必须写入+stderr,否则会破坏 MCP 协议流导致客户端判定"启动失败"。本脚本所有 print+均通过 stderr 输出。"""import asyncio@@ -15,19 +19,20 @@ def check_environment():if not base_url:print(- "警告: WEKNORA_BASE_URL 环境变量未设置,使用默认值: http://localhost:8080/api/v1"+ "警告: WEKNORA_BASE_URL 环境变量未设置,使用默认值: http://localhost:8080/api/v1",+ file=sys.stderr,)if not api_key:- print("警告: WEKNORA_API_KEY 环境变量未设置")+ print("警告: WEKNORA_API_KEY 环境变量未设置", file=sys.stderr)- print(f"WeKnora Base URL: {base_url or 'http://localhost:8080/api/v1'}")- print(f"API Key: {'已设置' if api_key else '未设置'}")+ print(f"WeKnora Base URL: {base_url or 'http://localhost:8080/api/v1'}", file=sys.stderr)+ print(f"API Key: {'已设置' if api_key else '未设置'}", file=sys.stderr)def main():"""主函数"""- print("启动 WeKnora MCP Server...")+ print("启动 WeKnora MCP Server...", file=sys.stderr)check_environment()try:@@ -35,13 +40,13 @@ def main():asyncio.run(run())except ImportError as e:- print(f"导入错误: {e}")- print("请确保已安装所有依赖: pip install -r requirements.txt")+ print(f"导入错误: {e}", file=sys.stderr)+ print("请确保已安装所有依赖: pip install -r requirements.txt", file=sys.stderr)sys.exit(1)except KeyboardInterrupt:- print("\n服务器已停止")+ print("\n服务器已停止", file=sys.stderr)except Exception as e:- print(f"服务器运行错误: {e}")+ print(f"服务器运行错误: {e}", file=sys.stderr)sys.exit(1)diff --git a/mcp-server/setup.py b/mcp-server/setup.pyindex 008d7c53d..0cae604be 100644--- a/mcp-server/setup.py+++ b/mcp-server/setup.py@@ -27,15 +27,15 @@ def read_requirements():setup(- name="weknora-mcp-server",- version="1.0.0",+ name="weknora-mcp",+ version="1.0.1",author="WeKnora Team",author_email="[email protected]",description="WeKnora MCP Server - Model Context Protocol server for WeKnora API",long_description=read_readme(),long_description_content_type="text/markdown",url="https://github.com/NannaOlympicBroadcast/WeKnoraMCP",- py_modules=["weknora_mcp_server", "main", "run_server", "run", "test_module"],+ py_modules=["weknora_mcp_server", "upload_paths", "main", "run_server", "run", "test_module"],classifiers=["Development Status :: 4 - Beta","Intended Audience :: Developers",diff --git a/mcp-server/test_stdio_stdout.py b/mcp-server/test_stdio_stdout.pynew file mode 100644index 000000000..ad807454a--- /dev/null+++ b/mcp-server/test_stdio_stdout.py@@ -0,0 +1,53 @@+#!/usr/bin/env python3+"""Regression: MCP stdio entry scripts must not write diagnostics to stdout."""++import subprocess+import sys+import unittest+from pathlib import Path++MCP_SERVER_DIR = Path(__file__).resolve().parent+++class StdioStdoutPurityTest(unittest.TestCase):+ def test_main_check_only_keeps_stdout_empty(self):+ result = subprocess.run(+ [sys.executable, "main.py", "--check-only"],+ capture_output=True,+ timeout=10,+ cwd=MCP_SERVER_DIR,+ )+ self.assertEqual(result.returncode, 0)+ self.assertEqual(+ result.stdout,+ b"",+ f"stdout must stay empty for MCP stdio compatibility, got: {result.stdout!r}",+ )+ self.assertTrue(+ result.stderr,+ "environment check output should appear on stderr",+ )++ def test_run_server_startup_keeps_stdout_empty(self):+ proc = subprocess.Popen(+ [sys.executable, "run_server.py"],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ cwd=MCP_SERVER_DIR,+ )+ try:+ stdout, stderr = proc.communicate(timeout=2)+ except subprocess.TimeoutExpired:+ proc.terminate()+ stdout, stderr = proc.communicate(timeout=5)++ self.assertEqual(+ stdout,+ b"",+ f"run_server.py must not write to stdout before JSON-RPC, got: {stdout!r}",+ )+ self.assertTrue(stderr, "startup diagnostics should appear on stderr")+++if __name__ == "__main__":+ unittest.main()diff --git a/mcp-server/weknora_mcp_server.py b/mcp-server/weknora_mcp_server.pyindex 38013ca11..c3f3de183 100644--- a/mcp-server/weknora_mcp_server.py+++ b/mcp-server/weknora_mcp_server.py@@ -1318,7 +1318,7 @@ def _init_options() -> InitializationOptions:"""Build MCP InitializationOptions (shared across all transports)"""return InitializationOptions(server_name="weknora-server",- server_version="1.0.0",+ server_version="1.0.1",capabilities=app.get_capabilities(notification_options=NotificationOptions(),experimental_capabilities={},