diff --git a/docs/mcp-namespace-health.md b/docs/mcp-namespace-health.md new file mode 100644 index 0000000..f73ece1 --- /dev/null +++ b/docs/mcp-namespace-health.md @@ -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 `. +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. diff --git a/gitea_mcp_server.py b/gitea_mcp_server.py index 099021f..1b141e2 100644 --- a/gitea_mcp_server.py +++ b/gitea_mcp_server.py @@ -180,6 +180,7 @@ MERGER_WORKTREE_ENV = "GITEA_MERGER_WORKTREE" RECONCILER_WORKTREE_ENV = "GITEA_RECONCILER_WORKTREE" import namespace_workspace_binding as nwb # noqa: E402 +import mcp_namespace_health # noqa: E402 def _preflight_in_test_mode() -> bool: @@ -8316,6 +8317,37 @@ def gitea_list_profiles() -> dict: 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() def gitea_activate_profile( profile_name: str, diff --git a/mcp_namespace_health.py b/mcp_namespace_health.py new file mode 100644 index 0000000..3ad7c3f --- /dev/null +++ b/mcp_namespace_health.py @@ -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"} + diff --git a/test_mcp_conn.py b/test_mcp_conn.py index 0dfec76..1667a60 100644 --- a/test_mcp_conn.py +++ b/test_mcp_conn.py @@ -1,20 +1,40 @@ #!/usr/bin/env python3 """Live health-check script to verify Gitea MCP namespace connections. -Spawns the MCP server processes as defined in the IDE's global config, -performs the JSON-RPC handshake, and queries the tools list to verify -that the connection is fully operational and doesn't return EOF. +Spawns MCP server processes from the IDE config, performs the JSON-RPC +handshake, verifies the required tool is registered, and invokes that tool. +The final invocation is what catches client/namespace EOF failures that a +static FastMCP registration check cannot see. """ + +import argparse import json import os import subprocess 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}'...") command = config.get("command") args = config.get("args", []) env = config.get("env", {}) + tool_name = required_tool or REQUIRED_NAMESPACE_TOOLS.get(name) or "gitea_whoami" # Merge current environment run_env = os.environ.copy() @@ -31,8 +51,16 @@ def run_connection_test(name, config): bufsize=1, env=run_env ) - except Exception as e: - print(f" [FAIL] Failed to spawn process: {e}") + except Exception as exc: + 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 # Send initialize request @@ -48,26 +76,35 @@ def run_connection_test(name, config): } try: - proc.stdin.write(json.dumps(init_req) + "\n") - proc.stdin.flush() + _write_message(proc, init_req) # Read response - line = proc.stdout.readline() - if not line: - stderr_content = proc.stderr.read() + res, stderr_content = _read_json_line(proc) + if res is None: 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() return False - print(f" [OK] Received initialize response: {line.strip()[:150]}...") + print(f" [OK] Received initialize response: {str(res)[:150]}...") # Send initialized notification init_notif = { "jsonrpc": "2.0", "method": "notifications/initialized" } - proc.stdin.write(json.dumps(init_notif) + "\n") - proc.stdin.flush() + _write_message(proc, init_notif) # Send tools/list request list_req = { @@ -76,16 +113,26 @@ def run_connection_test(name, config): "params": {}, "id": 2 } - proc.stdin.write(json.dumps(list_req) + "\n") - proc.stdin.flush() + _write_message(proc, list_req) - line = proc.stdout.readline() - if not line: + res, stderr_content = _read_json_line(proc) + if res is None: 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() return False - res = json.loads(line) if "error" in res: print(f" [FAIL] Server returned error: {res['error']}") proc.terminate() @@ -94,16 +141,111 @@ def run_connection_test(name, config): tools = res.get("result", {}).get("tools", []) tool_names = [t.get("name") for t in tools] print(f" [OK] Successfully retrieved {len(tool_names)} tools: {tool_names[:5]}...") + if tool_name not in tool_names: + assessment = classify_namespace_probe( + name, + required_tool=tool_name, + 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() + 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 e: - print(f" [FAIL] Error during handshake: {e}") + except Exception as exc: + print(f" [FAIL] Error during handshake: {exc}") proc.terminate() return False + 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: with open(config_path) as f: mcp_config = json.load(f) @@ -112,10 +254,16 @@ def main(): sys.exit(1) servers = mcp_config.get("mcpServers", {}) + namespaces = args.namespaces or list(REQUIRED_NAMESPACE_TOOLS) failed = False - for name in ["gitea-author", "gitea-reviewer"]: + for name in namespaces: 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 else: print(f"Server '{name}' not found in mcp_config.json") diff --git a/tests/test_mcp_namespace_health.py b/tests/test_mcp_namespace_health.py new file mode 100644 index 0000000..8f06ee4 --- /dev/null +++ b/tests/test_mcp_namespace_health.py @@ -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()