fix(mcp-server): route diagnostics to stderr to fix stdio protocol crash (#2371)

* fix(mcp-server): route diagnostics to stderr to fix stdio protocol crash

Entry scripts (run_server.py, main.py, run.py) printed diagnostics to
stdout via bare print(). Under the stdio transport (the default and the
path used by all MCP clients per MCP_CONFIG.md: `uv run run_server.py`),
stdout is the JSON-RPC channel, so the plain-text lines emitted before
the initialize handshake corrupted the protocol stream. Strict MCP clients
(Claude Desktop / Cursor / ZCode / VS Code Copilot) treated this as a
fatal protocol error and reported the server as failed-to-start.

Redirect all diagnostic print() to sys.stderr (per MCP spec, only
JSON-RPC may use stdout). weknora_mcp_server.py already routes through
logging (stderr) and is unchanged.

Verified against a live backend (initialize -> tools/list (28 tools) ->
tools/call list_knowledge_bases); stdout first byte is now '{' with all
diagnostics on stderr.

* chore(mcp-server): publish package name as weknora-mcp

Rename the PyPI distribution name from weknora-mcp-server to weknora-mcp
(tools used: pyproject [project].name + setup.py name). The installed
console-script commands (weknora-mcp-server, weknora-server) and the
Python module (weknora_mcp_server) are unchanged for backward compatibility.

* fix(mcp-server): include upload_paths in wheel + bump to 1.0.1

The 1.0.0 wheel was missing upload_paths.py: it was absent from the
[tool.setuptools] py-modules list (and setup.py py_modules), so setuptools
never packed it. weknora_mcp_server.py line 26 does
`from upload_paths import resolve_upload_file_path, set_active_transport`,
so any path that fully imports the module — i.e. the MCP client initialize
handshake — crashed with ModuleNotFoundError. `--version` survived only
because argparse exits before that import runs.

Fix: add 'upload_paths' to py-modules (pyproject.toml + setup.py) and bump
to 1.0.1 (1.0.0 is immutable on PyPI). Also sync the user-facing version
strings (__version__, server_version, main --version) to 1.0.1.

* ci(mcp-server): add workflow.yml to build & publish to PyPI via OIDC

Adds .github/workflows/workflow.yml adapted from annopick/tuomin's ci.yml:
- test: matrix Python 3.10–3.13 (matches requires-python >=3.10), runs the
  flat test_*.py suite in mcp-server/
- build: on mcp-server-v* tags, builds sdist + wheel via uv build, and
  guards against the 1.0.0 regression by asserting upload_paths.py is in
  the wheel before publishing
- publish: PyPI Trusted Publishing (OIDC, id-token: write) to weknora-mcp,
  no API token needed

Publishing is gated on tags named mcp-server-v* to decouple from the Go
release workflow that already targets v* tags.

* fix(mcp-server): route diagnostics to stderr and fix packaging/CI

Prevent MCP stdio startup crashes by sending entry-script diagnostics to
stderr, package upload_paths in the wheel, and add unittest-based CI with
stdout purity regression tests.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
main
annopick 2026-07-28 21:23:09 +08:00 committed by GitHub
parent c9a342d965
commit 400bbbf717
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 351 additions and 42 deletions

106
.github/workflows/mcp-server.yml vendored 100644
View File

@ -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/v1

115
.github/workflows/workflow.yml vendored 100644
View File

@ -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/v1

View File

@ -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
### 新增

View File

@ -1,6 +1,8 @@
# 使用 uv 运行 WeKnora MCP 服务器
> 更推荐使用`uv`来运行基于python的MCP服务。
>
> 也可通过 PyPI 安装:`pip install weknora-mcp`(包名 `weknora-mcp`,非 `weknora-mcp-server`)。
## 1. 安装 uv

View File

@ -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`。
### 开发模式安装
```bash
pip install -e .

View File

@ -5,10 +5,10 @@ WeKnora MCP Server Package
A 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"]

View File

@ -7,6 +7,10 @@ WeKnora MCP Server 主入口点
1. python main.py
2. python -m weknora_mcp_server
3. weknora-mcp-server (安装后)
注意:在 stdio 传输下,stdout 是 JSON-RPC 通道,所有诊断/提示信息必须写入
stderr,否则会破坏 MCP 协议流导致客户端判定"启动失败"。本文件所有 print
均通过 stderr 输出。
"""
import argparse
@ -32,8 +36,8 @@ def check_dependencies():
return True
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)
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 logging
logging.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 traceback

View File

@ -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]

View File

@ -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)

View File

@ -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)

View File

@ -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="support@weknora.com",
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",

View File

@ -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()

View File

@ -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={},