Files
codex-app-server/cloud/websearch_mcp.py
host f39ed3654e ci3: lint/mypy 第二阶段清理 + 覆盖率 76% -> 78%(门槛不动)
基底:#251 头 174b631(堆叠于 #242 feat-ci-expand 之上),
基线 origin/main aebc6238;本轨不改 #251 已定语义、不动
workflow 门槛、不删检查、不加 skip。

lint(ruff E,F@120):109 -> 10
- F401 43 -> 0:删未用导入;try/except 双绑定的名字出现
  “打地鼠”(删 except 分支后 try 分支又被标出),两分支
  均已核对正文无引用后清掉;MCP 三模块的 Error 名不删,
  改走 importlib 属性绑定(见下),两路径绑定都保留。
- E702 40 -> 0:全在 host.py main() 的 argparse 段,纯分行,
  tokenize 按分号 token 拆(含 2377 行多行语句只断首个分号);
  一次 5 空格缩进失误已回滚重做并以 ast + 全量 host 测试验证。
- E501 13 -> 0:host.py 5 项随 E702 分行连带清掉;mcp_server
  3 项把描述拆成相邻字面量(AST 比对 24 条工具描述与原值
  完全一致,注意 ruff 按东亚宽度计长,CJK 算 2);test_host
  5 项断开 git commit 参数表。
- E402 8 -> 10:生产侧 2 项清掉(db.py _re、github_app
  _base64 移到顶部,之前无引用、无重名);剩余 10 项全是
  tests/ 的 sys.path 前置 import(6 项旧 + 4 个新测试文件
  沿用同一既定模式),移上去会破坏单文件直跑,有意保留。
- F841 4 -> 0:只去绑定、不删调用(run_task、DB 入队、
  tarfile 上下文、git 提交),各有注释与原测试/新测试覆盖;
  host dispatch_from_branch 新增真实 git 仓库回归测试。
- F811 1 -> 0:server 本地 _row_get 与 peer_messages.row_get
  逐行相同,删本地定义,全部调用点解析到同一 import;
  新增 test_server_row_get(同一对象 + 三路行为)。

mypy(生产范围):24 -> 0,零新增 type: ignore
- no-redef 9 -> 0:MCP 三模块 try/except 两次 from-import
  改 importlib.import_module + 属性绑定(cloud 优先、flat
  copy 回落、内层 ImportError 同样回落,语义与原来一致;
  flat-copy 子进程测试证实回落后 __module__ 为顶层名);
  server _row_get 随 F811 消除。
- arg-type 10 -> 0:harness2_tasks shared 改 TypedDict
  逐键精确类型;CodexProbeAdapter 补 no-op validate_tree
  (_adapter_validate 本就跳过缺失方法,行为一致)。
- var-annotated 3 -> 0:sub2api _SHARED_ADMIN/_login_slots、
  verify-multiuser RESULTS 加精确注解。
- assignment/misc 2 -> 0:marker_tools ZoneInfo 先声明
  Any 再 try import(草稿先验 mypy 通过)。

bandit:总数 286 不变,High 仍 4 项,全在 host.py,本轨不改
(属第 3 项白名单轨范围),只做 triage:
- 1319 run_verify:无插值,整串验测命令,管道/&& 须 shell
  语义(新增 test_host_run_verify 断言管道与 && 真实生效)。
- 1497 notify:模板来自算子配置,三处插值全部 shlex.quote,
  证据为既有 test_notify_failure_quotes_shell_metacharacters
  (; touch 与 $(touch ) 不执行)。
- 2099/2103 goal verify:无插值,任务配置验测串,同 run_verify。
- 无新增 High;pip-audit 0 漏洞。

覆盖率(同口径三套件 coverage 计量):75.96% -> 77.87%
(22392 行/缺 5385 -> 22437 行/缺 4963,显示 76% -> 78%)
- client.py 0% -> 90%(pipe 假子进程 + main 分支)
- run_parallel.py 0% -> 97%、migrate 包装 0% -> 95%
- playwright_mcp 37% -> 62%、imagegen_mcp 47% -> 79%、
  websearch_mcp 51% -> 86%、deploy.py 56% -> 77%
- verify-multiuser 0% -> 27%(仅 check/req helper;main()
  是主机侧真实多用户实弹验证,按门禁不建生产任务、
  不以 mock 冒充,仍为缺口)
- host.py 55% -> 57%(文件 2020 -> 2060 行系 E702 分行
  的计量口径变化,非代码膨胀)
- 未到 85%:门槛保持 75% 不动,不删低覆盖模块出统计口径;
  缺口主力仍是 server.py / worker.py / host.py 大文件,
  下一阶段须针对性深测,非本轨快赢可及。

验证:三套件 1576 -> 1629 项全过(tests 127、cloud/tests
1449 skipped=4、deploy/tests 53);ruff E9 通过;mypy 0;
bandit High 4(同上);pip-audit 0 漏洞;试跑产物已删,
提交后工作树干净。
2026-11-03 02:48:54 +00:00

248 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Stdio MCP server exposing web_search / web_fetch to codex.
Protocol: JSON-RPC 2.0 over stdio, one JSON object per line.
Logs go to stderr only -- anything on stdout would corrupt the
JSON-RPC stream.
This file is deliberately thin: all provider logic lives in
``websearch.py``. It can run two ways:
- inside the repo: ``python3 -m cloud.websearch_mcp`` (imports
``cloud.websearch``);
- copied flat into a tenant codex-home next to ``websearch.py``
(imports plain ``websearch`` from its own directory).
The ``ensure_codex_home_websearch`` helper in websearch.py does the
copying; it never writes API keys into config.toml -- keys are read
from the MCP server process environment by websearch.py.
"""
import importlib
import json
import os
import sys
# cloud 包优先、租户 flat copy 回落(与 playwright_mcp 同款理由:
# 两次 from-import 会让 mypy 报 no-redef,importlib 属性绑定
# 在两条路径下都是同一组名字;cloud 导入本身的 ImportError
# 同样回落,与原来 except 语义一致)。
try:
_mcp_backend = importlib.import_module("cloud.websearch")
except ImportError: # flat copy in a tenant codex-home
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
_mcp_backend = importlib.import_module("websearch")
WebSearchError = _mcp_backend.WebSearchError
fetch_best = _mcp_backend.fetch_best
search = _mcp_backend.search
SERVER_NAME = "websearch"
SERVER_VERSION = "0.1.0"
_TOOLS = [
{
"name": "web_search",
"description": (
"Search the web and return ranked results with title, URL "
"and snippet, plus a synthesised answer when the provider "
"supplies one. Use web_fetch to read specific pages. "
"provider may be 'auto' (frozen default: keyless SearXNG "
"first, then DuckDuckGo as the free fallback, falling "
"back on failure; the paid backends Perplexity, Exa, "
"Tavily and Brave are NOT in the default chain even "
"when their keys are set, and a SearXNG failure never "
"falls back to a paid backend, so default use never "
"incurs paid cost) or a single provider name to pin it "
"(pinning a paid backend still calls it: that is an "
"explicit override, not a default). Set "
"WEBSEARCH_ENABLE_PAID=1 to restore the old default "
"chain (Perplexity, Exa, Tavily, Brave, SearXNG, "
"DuckDuckGo); unfreezing is explicit and may incur "
"paid cost. "
"scope 'code' restricts results to programming sources "
"only (official language docs, GitHub, package "
"registries, Stack Overflow, CVE/NVD); anything else "
"is filtered out, never returned. Default scope "
"'general' is unfiltered. With scope 'code' only, "
"allowed_hosts may name extra project domains for "
"this call (explicit allowlist extension, subdomains "
"included, dot-boundary matched); it is not an "
"arbitrary-site search, and it is rejected with "
"scope 'general'. This tool does not do "
"shopping, social, places, travel, general news, "
"weather, finance, or browser checkout."
),
"inputSchema": {
"type": "object",
"properties": {
"query": {"type": "string",
"description": "Search query"},
"limit": {"type": "integer", "default": 5,
"description": "Max results, 1-10"},
"provider": {"type": "string", "default": "auto",
"description": "auto or a provider name"},
"scope": {"type": "string", "default": "general",
"enum": ["general", "code"],
"description": "general: unfiltered web "
"search. code: programming "
"sources only, see tool "
"description."},
"allowed_hosts": {"type": "array",
"items": {"type": "string"},
"description": "Only with scope "
"'code': extra "
"domains for this "
"call only, on top "
"of the builtin "
"programming list. "
"Omit for no "
"extension; empty, "
"wildcard, or "
"non-hostname "
"values are "
"rejected, never "
"silently ignored."},
},
"required": ["query"],
},
},
{
"name": "web_fetch",
"description": (
"Fetch one URL and return clean text plus its links, "
"truncated head+tail when over char_limit. "
"Extraction first: Tavily extract, then Exa contents "
"(only backends with a configured key are tried), "
"direct fetch last. Under the egress proxy, direct "
"fetch of a domain outside the Tinyproxy whitelist "
"fails 403 fail-closed; that error is reported, not "
"bypassed. Only http(s) URLs; localhost / private IPs "
"are blocked. This is not a sandbox boundary."
),
"inputSchema": {
"type": "object",
"properties": {
"url": {"type": "string",
"description": "URL to fetch"},
"char_limit": {"type": "integer", "default": 15000,
"description": "Max characters, "
"clamped 2000-500000"},
},
"required": ["url"],
},
},
]
def _err(code, message):
return {"code": code, "message": message}
def handle_request(request, search_fn=None, fetch_fn=None):
"""Handle one JSON-RPC request dict. Returns a response dict or
None for notifications (no id). Pure function for testability:
the stdio loop passes the real search/fetch, tests pass fakes."""
search_fn = search_fn or search
fetch_fn = fetch_fn or fetch_best
if not isinstance(request, dict):
return {"jsonrpc": "2.0", "id": None,
"error": _err(-32700, "request is not an object")}
method = request.get("method")
req_id = request.get("id")
is_notification = "id" not in request
if method == "initialize":
if is_notification:
return None
return {"jsonrpc": "2.0", "id": req_id,
"result": {
"protocolVersion": request.get("params", {}).get(
"protocolVersion", "2024-11-05"),
"capabilities": {"tools": {}},
"serverInfo": {"name": SERVER_NAME,
"version": SERVER_VERSION}}}
if method in ("notifications/initialized", "notifications/cancelled"):
return None
if method == "ping":
if is_notification:
return None
return {"jsonrpc": "2.0", "id": req_id, "result": {}}
if method == "tools/list":
if is_notification:
return None
return {"jsonrpc": "2.0", "id": req_id,
"result": {"tools": _TOOLS}}
if method == "tools/call":
if is_notification:
return None
params = request.get("params") or {}
name = params.get("name")
args = params.get("arguments") or {}
try:
if name == "web_search":
# allowed_hosts is passed through only when the
# caller supplied it, so older search_fn fakes
# without that parameter keep working.
search_kwargs = {}
if "allowed_hosts" in args:
search_kwargs["allowed_hosts"] = \
args.get("allowed_hosts")
result = search_fn(
args.get("query"),
limit=args.get("limit", 5),
provider=args.get("provider", "auto"),
scope=args.get("scope", "general"),
**search_kwargs)
elif name == "web_fetch":
result = fetch_fn(
args.get("url"),
char_limit=args.get("char_limit", 15000))
else:
return {"jsonrpc": "2.0", "id": req_id,
"error": _err(-32602, "unknown tool: %r" % name)}
except Exception as exc: # noqa: BLE001 - tool errors are data
# WebSearchError messages are already key-free by
# construction in websearch.py; other exceptions are
# rendered as type + message, never with env or headers.
return {"jsonrpc": "2.0", "id": req_id,
"result": {"content": [{"type": "text",
"text": "error: %s" % exc}],
"isError": True}}
return {"jsonrpc": "2.0", "id": req_id,
"result": {"content": [{"type": "text",
"text": json.dumps(
result, ensure_ascii=False)}],
"isError": False}}
if is_notification:
return None
return {"jsonrpc": "2.0", "id": req_id,
"error": _err(-32601, "method not found: %r" % method)}
def main():
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
request = json.loads(line)
except json.JSONDecodeError as exc:
sys.stdout.write(json.dumps(
{"jsonrpc": "2.0", "id": None,
"error": _err(-32700, "parse error: %s" % exc)}) + "\n")
sys.stdout.flush()
continue
try:
response = handle_request(request)
except Exception as exc: # noqa: BLE001 - server must not die
print("websearch_mcp: handler error: %s" % exc, file=sys.stderr)
if "id" in request:
response = {"jsonrpc": "2.0", "id": request["id"],
"error": _err(-32603, "internal error")}
else:
response = None
if response is not None:
sys.stdout.write(json.dumps(response) + "\n")
sys.stdout.flush()
if __name__ == "__main__":
main()