feat: diagnose live MCP namespace EOF health

This commit is contained in:
2026-07-09 10:59:34 -04:00
parent cc4b95839d
commit 05fdceee5f
5 changed files with 540 additions and 24 deletions
+54
View File
@@ -0,0 +1,54 @@
# MCP namespace EOF recovery
Gitea MCP tools can be registered in the Python FastMCP server while the IDE's
live MCP namespace is still unusable. The failure usually appears as
`client is closing: EOF`, `transport closed`, or an empty response when calling
a tool such as `gitea_whoami`.
Do not treat static tool registration as proof that review or merge workflows
can proceed. A reviewer or merger flow must have live namespace evidence that
the required tool is callable through the configured namespace.
## Required namespace probes
Run the health check after changing MCP config, switching branches that affect
server code, or seeing EOF from any Gitea namespace:
```bash
python3 test_mcp_conn.py --config ~/.gemini/config/mcp_config.json
```
By default the script checks these namespaces and required tools:
| Namespace | Required tool |
| --- | --- |
| `gitea-author` | `gitea_whoami` |
| `gitea-reviewer` | `gitea_whoami` |
| `gitea-merger` | `gitea_whoami` |
| `gitea-tools` | `gitea_list_profiles` |
Use `--namespace gitea-reviewer` to test only one namespace. A passing probe
requires:
1. The namespace exists in the MCP config.
2. JSON-RPC initialize succeeds.
3. `tools/list` returns the required tool.
4. `tools/call` successfully invokes the required tool.
## Recovery steps
When a namespace returns EOF:
1. Note the reported namespace, required tool, PID, profile, environment
summary, and config path.
2. Stop any stale MCP server process for that PID.
3. Reload or touch the MCP config so the IDE reconnects the namespace.
4. Verify the namespace command, args, profile env, and checkout path point at
the current repository.
5. Re-run `python3 test_mcp_conn.py --namespace <name>`.
6. Resume review or merge work only after the required tool call passes.
The read-only `gitea_assess_mcp_namespace_health` tool can classify probe
evidence supplied by a client. It intentionally distinguishes
`required_tool_registered=true` from `required_tool_callable=false`; the latter
must block reviewer and merger workflows until the live namespace is repaired.
+32
View File
@@ -180,6 +180,7 @@ MERGER_WORKTREE_ENV = "GITEA_MERGER_WORKTREE"
RECONCILER_WORKTREE_ENV = "GITEA_RECONCILER_WORKTREE" RECONCILER_WORKTREE_ENV = "GITEA_RECONCILER_WORKTREE"
import namespace_workspace_binding as nwb # noqa: E402 import namespace_workspace_binding as nwb # noqa: E402
import mcp_namespace_health # noqa: E402
def _preflight_in_test_mode() -> bool: def _preflight_in_test_mode() -> bool:
@@ -8316,6 +8317,37 @@ def gitea_list_profiles() -> dict:
return {"profiles": profiles_out} return {"profiles": profiles_out}
@mcp.tool()
def gitea_assess_mcp_namespace_health(
namespace: str,
required_tool: str | None = None,
registered_tools: list[str] | None = None,
probe_result: dict | None = None,
process: dict | None = None,
config_path: str | None = None,
profile: str | None = None,
configured: bool = True,
) -> dict:
"""Read-only: classify live MCP namespace health for required Gitea tools.
Static FastMCP registration is not enough to prove a namespace works: IDE
clients can keep a registered tool list while live calls fail with
``client is closing: EOF``. This diagnostic accepts static registration
evidence plus live invocation evidence and returns fail-closed guidance for
reviewer/merger workflows.
"""
return mcp_namespace_health.classify_namespace_probe(
namespace,
required_tool=required_tool,
registered_tools=registered_tools,
probe_result=probe_result,
process=process,
config_path=config_path,
profile=profile,
configured=configured,
)
@mcp.tool() @mcp.tool()
def gitea_activate_profile( def gitea_activate_profile(
profile_name: str, profile_name: str,
+197
View File
@@ -0,0 +1,197 @@
"""Assess live MCP namespace health without trusting static registration.
The IDE/client namespace can fail with EOF even when this Python process still
registers the Gitea tools with FastMCP. These helpers keep that distinction
explicit so reviewer/merger flows can fail closed on the live path.
"""
from __future__ import annotations
from typing import Any
REQUIRED_NAMESPACE_TOOLS = {
"gitea-author": "gitea_whoami",
"gitea-reviewer": "gitea_whoami",
"gitea-merger": "gitea_whoami",
"gitea-tools": "gitea_list_profiles",
}
DEFAULT_NAMESPACES = tuple(REQUIRED_NAMESPACE_TOOLS)
EOF_PATTERNS = (
"client is closing: eof",
"transport closed",
"connection closed",
"broken pipe",
"end of file",
"eof",
)
SAFE_ENV_KEYS = (
"GITEA_MCP_PROFILE",
"GITEA_PROFILE_NAME",
"GITEA_SERVICE",
"GITEA_EXECUTION_ROLE",
"GITEA_MCP_CONFIG",
)
def _as_list(value: Any) -> list[str] | None:
if value is None:
return None
if isinstance(value, (list, tuple, set)):
return [str(v) for v in value]
return [str(value)]
def _contains_eof(text: str | None) -> bool:
lowered = (text or "").lower()
return any(pattern in lowered for pattern in EOF_PATTERNS)
def _safe_env_summary(process: dict[str, Any] | None) -> dict[str, str]:
if not process:
return {}
env = process.get("env") or process.get("environment") or {}
if not isinstance(env, dict):
return {}
return {
key: str(env[key])
for key in SAFE_ENV_KEYS
if key in env and env[key] not in (None, "")
}
def classify_namespace_probe(
namespace: str,
*,
required_tool: str | None = None,
registered_tools: list[str] | tuple[str, ...] | set[str] | None = None,
probe_result: dict[str, Any] | None = None,
process: dict[str, Any] | None = None,
config_path: str | None = None,
profile: str | None = None,
configured: bool = True,
) -> dict[str, Any]:
"""Classify whether a required tool is callable through a live namespace.
``registered_tools`` is static/server-side evidence. ``probe_result`` is
live client evidence from a real namespace invocation. The assessment is
healthy only when the required tool is registered and callable.
"""
ns = (namespace or "").strip()
tool = required_tool or REQUIRED_NAMESPACE_TOOLS.get(ns) or "gitea_whoami"
registered_list = _as_list(registered_tools)
registered = None if registered_list is None else tool in registered_list
probe = probe_result or {}
probe_success = bool(probe.get("success"))
error_message = str(
probe.get("error")
or probe.get("message")
or probe.get("stderr")
or probe.get("exception")
or ""
)
error_type = str(probe.get("error_type") or "").strip()
if not error_type and error_message:
if _contains_eof(error_message):
error_type = "namespace_eof"
elif "timeout" in error_message.lower():
error_type = "namespace_timeout"
else:
error_type = "namespace_call_failed"
if not configured:
error_type = "namespace_not_configured"
elif registered is False:
error_type = "tool_missing"
elif not probe_result:
error_type = "live_probe_missing"
elif not probe_success and not error_type:
error_type = "namespace_call_failed"
callable_live = bool(configured and probe_result and probe_success)
healthy = bool(configured and registered is not False and callable_live)
process_pid = process.get("pid") if isinstance(process, dict) else None
profile_name = profile or (
process.get("profile") if isinstance(process, dict) else None
)
env_summary = _safe_env_summary(process)
reasons: list[str] = []
if not configured:
reasons.append(f"MCP namespace '{ns}' is not configured.")
if registered is False:
reasons.append(
f"Required tool '{tool}' is not registered in namespace '{ns}'."
)
if error_type == "live_probe_missing":
reasons.append(
f"No live client invocation proof was supplied for '{ns}.{tool}'."
)
elif error_type == "namespace_eof":
reasons.append(
f"Live MCP namespace '{ns}' returned EOF while invoking '{tool}'."
)
elif error_type == "namespace_timeout":
reasons.append(
f"Live MCP namespace '{ns}' timed out while invoking '{tool}'."
)
elif error_type == "namespace_call_failed":
reasons.append(
f"Live MCP namespace '{ns}' failed while invoking '{tool}'."
)
remediation = []
if not healthy:
remediation.append(
"Restart or reconnect the IDE MCP client namespace, then retry "
f"'{tool}' through namespace '{ns}'."
)
remediation.append(
"Reload the MCP config and verify the configured command, args, "
"profile environment, and working tree point at the current checkout."
)
if process_pid:
remediation.append(
f"If PID {process_pid} belongs to a stale MCP process, stop it "
"before reconnecting the namespace."
)
else:
remediation.append(f"Namespace '{ns}' can invoke '{tool}'.")
return {
"success": healthy,
"healthy": healthy,
"namespace": ns,
"required_tool": tool,
"configured": configured,
"registered_tools_checked": registered_list is not None,
"required_tool_registered": registered,
"required_tool_callable": callable_live,
"error_type": None if healthy else error_type,
"error_message": error_message or None,
"reasons": reasons,
"remediation": remediation,
"diagnostics": {
"namespace": ns,
"required_tool": tool,
"process_pid": process_pid,
"profile": profile_name,
"env": env_summary,
"config_path": config_path,
},
"blocks_merge_workflow": namespace_health_blocks_task(
"merge_pr", healthy
),
}
def namespace_health_blocks_task(task: str, healthy: bool) -> bool:
"""Return whether a broken namespace must block a workflow task."""
if healthy:
return False
return (task or "").strip() in {"merge_pr", "review_pr", "submit_review"}
+175 -27
View File
@@ -1,20 +1,40 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Live health-check script to verify Gitea MCP namespace connections. """Live health-check script to verify Gitea MCP namespace connections.
Spawns the MCP server processes as defined in the IDE's global config, Spawns MCP server processes from the IDE config, performs the JSON-RPC
performs the JSON-RPC handshake, and queries the tools list to verify handshake, verifies the required tool is registered, and invokes that tool.
that the connection is fully operational and doesn't return EOF. The final invocation is what catches client/namespace EOF failures that a
static FastMCP registration check cannot see.
""" """
import argparse
import json import json
import os import os
import subprocess import subprocess
import sys import sys
def run_connection_test(name, config): from mcp_namespace_health import REQUIRED_NAMESPACE_TOOLS, classify_namespace_probe
def _read_json_line(proc):
line = proc.stdout.readline()
if not line:
stderr_content = proc.stderr.read()
return None, stderr_content
return json.loads(line), None
def _write_message(proc, payload):
proc.stdin.write(json.dumps(payload) + "\n")
proc.stdin.flush()
def run_connection_test(name, config, *, required_tool=None, config_path=None):
print(f"Testing MCP connection for '{name}'...") print(f"Testing MCP connection for '{name}'...")
command = config.get("command") command = config.get("command")
args = config.get("args", []) args = config.get("args", [])
env = config.get("env", {}) env = config.get("env", {})
tool_name = required_tool or REQUIRED_NAMESPACE_TOOLS.get(name) or "gitea_whoami"
# Merge current environment # Merge current environment
run_env = os.environ.copy() run_env = os.environ.copy()
@@ -31,8 +51,16 @@ def run_connection_test(name, config):
bufsize=1, bufsize=1,
env=run_env env=run_env
) )
except Exception as e: except Exception as exc:
print(f" [FAIL] Failed to spawn process: {e}") print(f" [FAIL] Failed to spawn process: {exc}")
assessment = classify_namespace_probe(
name,
required_tool=tool_name,
probe_result={"success": False, "error": str(exc)},
process={"profile": env.get("GITEA_MCP_PROFILE"), "env": env},
config_path=config_path,
)
print(f" diagnostics: {json.dumps(assessment['diagnostics'], sort_keys=True)}")
return False return False
# Send initialize request # Send initialize request
@@ -48,26 +76,35 @@ def run_connection_test(name, config):
} }
try: try:
proc.stdin.write(json.dumps(init_req) + "\n") _write_message(proc, init_req)
proc.stdin.flush()
# Read response # Read response
line = proc.stdout.readline() res, stderr_content = _read_json_line(proc)
if not line: if res is None:
stderr_content = proc.stderr.read()
print(f" [FAIL] Received EOF from process. Stderr:\n{stderr_content}") print(f" [FAIL] Received EOF from process. Stderr:\n{stderr_content}")
assessment = classify_namespace_probe(
name,
required_tool=tool_name,
probe_result={"success": False, "error": stderr_content or "EOF"},
process={
"pid": proc.pid,
"profile": env.get("GITEA_MCP_PROFILE"),
"env": env,
},
config_path=config_path,
)
print(f" remediation: {' '.join(assessment['remediation'])}")
proc.terminate() proc.terminate()
return False return False
print(f" [OK] Received initialize response: {line.strip()[:150]}...") print(f" [OK] Received initialize response: {str(res)[:150]}...")
# Send initialized notification # Send initialized notification
init_notif = { init_notif = {
"jsonrpc": "2.0", "jsonrpc": "2.0",
"method": "notifications/initialized" "method": "notifications/initialized"
} }
proc.stdin.write(json.dumps(init_notif) + "\n") _write_message(proc, init_notif)
proc.stdin.flush()
# Send tools/list request # Send tools/list request
list_req = { list_req = {
@@ -76,16 +113,26 @@ def run_connection_test(name, config):
"params": {}, "params": {},
"id": 2 "id": 2
} }
proc.stdin.write(json.dumps(list_req) + "\n") _write_message(proc, list_req)
proc.stdin.flush()
line = proc.stdout.readline() res, stderr_content = _read_json_line(proc)
if not line: if res is None:
print(" [FAIL] Received EOF on tools/list request.") print(" [FAIL] Received EOF on tools/list request.")
assessment = classify_namespace_probe(
name,
required_tool=tool_name,
probe_result={"success": False, "error": stderr_content or "EOF"},
process={
"pid": proc.pid,
"profile": env.get("GITEA_MCP_PROFILE"),
"env": env,
},
config_path=config_path,
)
print(f" remediation: {' '.join(assessment['remediation'])}")
proc.terminate() proc.terminate()
return False return False
res = json.loads(line)
if "error" in res: if "error" in res:
print(f" [FAIL] Server returned error: {res['error']}") print(f" [FAIL] Server returned error: {res['error']}")
proc.terminate() proc.terminate()
@@ -94,16 +141,111 @@ def run_connection_test(name, config):
tools = res.get("result", {}).get("tools", []) tools = res.get("result", {}).get("tools", [])
tool_names = [t.get("name") for t in tools] tool_names = [t.get("name") for t in tools]
print(f" [OK] Successfully retrieved {len(tool_names)} tools: {tool_names[:5]}...") print(f" [OK] Successfully retrieved {len(tool_names)} tools: {tool_names[:5]}...")
if tool_name not in tool_names:
proc.terminate() assessment = classify_namespace_probe(
return True name,
except Exception as e: required_tool=tool_name,
print(f" [FAIL] Error during handshake: {e}") registered_tools=tool_names,
probe_result={"success": False, "error": "required tool missing"},
process={
"pid": proc.pid,
"profile": env.get("GITEA_MCP_PROFILE"),
"env": env,
},
config_path=config_path,
)
print(f" [FAIL] Required tool '{tool_name}' is not registered.")
print(f" remediation: {' '.join(assessment['remediation'])}")
proc.terminate() proc.terminate()
return False return False
call_req = {
"jsonrpc": "2.0",
"method": "tools/call",
"params": {"name": tool_name, "arguments": {}},
"id": 3,
}
_write_message(proc, call_req)
call_res, stderr_content = _read_json_line(proc)
if call_res is None:
assessment = classify_namespace_probe(
name,
required_tool=tool_name,
registered_tools=tool_names,
probe_result={"success": False, "error": stderr_content or "EOF"},
process={
"pid": proc.pid,
"profile": env.get("GITEA_MCP_PROFILE"),
"env": env,
},
config_path=config_path,
)
print(f" [FAIL] Received EOF on {tool_name} invocation.")
print(f" diagnostics: {json.dumps(assessment['diagnostics'], sort_keys=True)}")
print(f" remediation: {' '.join(assessment['remediation'])}")
proc.terminate()
return False
if "error" in call_res:
assessment = classify_namespace_probe(
name,
required_tool=tool_name,
registered_tools=tool_names,
probe_result={"success": False, "error": call_res["error"]},
process={
"pid": proc.pid,
"profile": env.get("GITEA_MCP_PROFILE"),
"env": env,
},
config_path=config_path,
)
print(f" [FAIL] {tool_name} invocation returned error: {call_res['error']}")
print(f" remediation: {' '.join(assessment['remediation'])}")
proc.terminate()
return False
assessment = classify_namespace_probe(
name,
required_tool=tool_name,
registered_tools=tool_names,
probe_result={"success": True, "result": call_res.get("result")},
process={
"pid": proc.pid,
"profile": env.get("GITEA_MCP_PROFILE"),
"env": env,
},
config_path=config_path,
)
print(f" [OK] Successfully invoked required tool '{tool_name}'.")
print(f" diagnostics: {json.dumps(assessment['diagnostics'], sort_keys=True)}")
proc.terminate()
return True
except Exception as exc:
print(f" [FAIL] Error during handshake: {exc}")
proc.terminate()
return False
def main(): def main():
config_path = "/Users/jasonwalker/.gemini/config/mcp_config.json" parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
default=os.environ.get(
"MCP_CONFIG_PATH",
os.path.expanduser("~/.gemini/config/mcp_config.json"),
),
help="Path to MCP config JSON.",
)
parser.add_argument(
"--namespace",
action="append",
dest="namespaces",
help="Namespace to test. May be repeated.",
)
args = parser.parse_args()
config_path = args.config
try: try:
with open(config_path) as f: with open(config_path) as f:
mcp_config = json.load(f) mcp_config = json.load(f)
@@ -112,10 +254,16 @@ def main():
sys.exit(1) sys.exit(1)
servers = mcp_config.get("mcpServers", {}) servers = mcp_config.get("mcpServers", {})
namespaces = args.namespaces or list(REQUIRED_NAMESPACE_TOOLS)
failed = False failed = False
for name in ["gitea-author", "gitea-reviewer"]: for name in namespaces:
if name in servers: if name in servers:
if not run_connection_test(name, servers[name]): if not run_connection_test(
name,
servers[name],
required_tool=REQUIRED_NAMESPACE_TOOLS.get(name),
config_path=config_path,
):
failed = True failed = True
else: else:
print(f"Server '{name}' not found in mcp_config.json") print(f"Server '{name}' not found in mcp_config.json")
+85
View File
@@ -0,0 +1,85 @@
import unittest
import gitea_mcp_server
import mcp_namespace_health
class TestMcpNamespaceHealth(unittest.TestCase):
def test_registered_tool_but_live_eof_blocks_merge(self):
result = mcp_namespace_health.classify_namespace_probe(
"gitea-reviewer",
required_tool="gitea_whoami",
registered_tools=["gitea_whoami", "gitea_list_profiles"],
probe_result={
"success": False,
"error": "client is closing: EOF",
},
process={
"pid": 4321,
"profile": "prgs-reviewer",
"env": {
"GITEA_MCP_PROFILE": "prgs-reviewer",
"GITEA_TOKEN": "must-not-leak",
},
},
config_path="/Users/jasonwalker/.gemini/config/mcp_config.json",
)
self.assertFalse(result["healthy"])
self.assertEqual(result["error_type"], "namespace_eof")
self.assertTrue(result["required_tool_registered"])
self.assertFalse(result["required_tool_callable"])
self.assertTrue(result["blocks_merge_workflow"])
self.assertEqual(result["diagnostics"]["process_pid"], 4321)
self.assertEqual(result["diagnostics"]["profile"], "prgs-reviewer")
self.assertEqual(
result["diagnostics"]["env"]["GITEA_MCP_PROFILE"],
"prgs-reviewer",
)
self.assertNotIn("GITEA_TOKEN", result["diagnostics"]["env"])
self.assertIn("gitea-reviewer", result["reasons"][0])
self.assertIn("gitea_whoami", result["reasons"][0])
def test_successful_live_invocation_is_healthy(self):
result = mcp_namespace_health.classify_namespace_probe(
"gitea-author",
registered_tools=["gitea_whoami"],
probe_result={"success": True, "result": {"authenticated": True}},
process={"pid": 1234, "profile": "prgs-author"},
config_path="/tmp/mcp_config.json",
)
self.assertTrue(result["healthy"])
self.assertTrue(result["required_tool_registered"])
self.assertTrue(result["required_tool_callable"])
self.assertFalse(result["blocks_merge_workflow"])
self.assertIsNone(result["error_type"])
def test_registered_missing_required_tool_fails_before_probe_success(self):
result = mcp_namespace_health.classify_namespace_probe(
"gitea-tools",
registered_tools=["gitea_whoami"],
probe_result={"success": True, "result": {}},
)
self.assertFalse(result["healthy"])
self.assertEqual(result["required_tool"], "gitea_list_profiles")
self.assertFalse(result["required_tool_registered"])
self.assertEqual(result["error_type"], "tool_missing")
def test_server_tool_exposes_same_assessment(self):
result = gitea_mcp_server.gitea_assess_mcp_namespace_health(
"gitea-merger",
registered_tools=["gitea_whoami"],
probe_result={"success": False, "error": "transport closed"},
process={"pid": 9876, "profile": "prgs-merger"},
)
self.assertFalse(result["success"])
self.assertEqual(result["error_type"], "namespace_eof")
self.assertEqual(result["namespace"], "gitea-merger")
self.assertEqual(result["diagnostics"]["process_pid"], 9876)
if __name__ == "__main__":
unittest.main()