Skip to content
Closed
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
19347f3
fix(streaming): run MCP discovery off the turn's critical path
dankkush Aug 13, 2026
3b8a352
fix(streaming): assert profile home via contextvar in MCP discovery t…
dankkush Aug 13, 2026
68a3a42
fix(streaming): use version-gated override resolver in MCP discovery …
dankkush Aug 13, 2026
35d3e97
fix(streaming): bounded join + coalescing for background MCP discovery
dankkush Aug 14, 2026
99ea1a5
fix(streaming): synchronous fallback on agents without the home overr…
dankkush Aug 14, 2026
8228c2a
fix(streaming): profile-scoped MCP readiness instead of timed join
dankkush Aug 14, 2026
e017cf0
fix(streaming): generation-based single-flight MCP readiness
dankkush Aug 14, 2026
e088f4d
fix(commands): reload-mcp asserts the profile home during re-discovery
dankkush Aug 14, 2026
efe6309
fix(commands): reload-mcp authority is deterministic default profile
dankkush Aug 14, 2026
5a9e57b
fix(streaming): physically single-flight owners and canonical readine…
dankkush Aug 15, 2026
8c04b84
fix(commands): fail closed when a discovery owner survives the reload…
dankkush Aug 15, 2026
1fb90fc
fix(streaming): fence owner creation behind the reload teardown window
dankkush Aug 15, 2026
2736411
fix(streaming): hold the reload fence across the entire rebuild
dankkush Aug 15, 2026
118ca77
fix(commands): phase-split the reload fence; never stall first turns
dankkush Aug 17, 2026
9b96ad3
fix(streaming): timeout retirement wakes peer waiters
dankkush Aug 17, 2026
00380f4
fix(streaming): refreshable readiness, canonical keys, wait-loop hard…
dankkush Aug 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 131 additions & 3 deletions api/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from __future__ import annotations
from contextlib import nullcontext
import logging
import os
import threading
from typing import Any

Expand Down Expand Up @@ -269,8 +270,121 @@ def _run_reload_mcp_command() -> str:
with _lock:
old_servers = set(_servers.keys())

shutdown_mcp_servers()
new_tools = discover_mcp_tools()
# Route the re-discovery through the SAME readiness authority
# the stream worker uses (api.streaming), so a subsequent turn
# observes the fresh outcome instead of a stale 'completed' /
# 'failed' readiness recorded before this reload. The command
# waits on the shared readiness event so its synchronous
# report below is still accurate.
#
# The authority is keyed by the CANONICAL resolved default
# profile-home path (the same key the startup kickoff and
# default-profile turns consult). /reload-mcp is a GLOBAL
# operation (it shuts down and reconnects every configured
# server), so it deliberately does NOT key off the exec-time
# HERMES_HOME env: a concurrent stream can mutate that
# process-global while the command runs, which would make the
# reload capture another profile (Greptile P1).
from api.streaming import (
_MCP_READINESS_WAIT_CAP_S,
_MCP_RELOAD_FENCE,
_canonical_readiness_key,
_invalidate_mcp_readiness,
_mcp_retry_discovery,
_mcp_wait_readiness,
_prepare_global_reload,
)

def _reload_discover():
"""Re-discover MCP tools; returns bool.

Installs the DEFAULT profile-home override (like the
stream worker's discovery closure), so a background
reload run can never read another stream's HERMES_HOME
after env mutation (Greptile P1).
"""
_mcp_home_token = None
try:
from api.profiles import _resolve_hermes_home_override
_hc_mod = _resolve_hermes_home_override()
if _hc_mod is not None:
_mcp_home = getattr(
_hc_mod, 'get_default_hermes_root', lambda: ''
)()
if _mcp_home:
_mcp_home_token = _hc_mod.set_hermes_home_override(
str(_mcp_home)
)
try:
discover_mcp_tools()
return True
except Exception:
return False
finally:
if _mcp_home_token is not None:
_hc_mod.reset_hermes_home_override(_mcp_home_token)
except Exception:
return False
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

# Coordinate the global shutdown with every live discovery
# owner (cancel + bounded join) so a body mid-discovery cannot
# re-register old-config servers after the registry is cleared.
# Fail CLOSED: if any owner survived the join cap, abort the
# reload rather than run a discovery body concurrently with a
# registry rebuild (Greptile review round 10).
#
# The owner-creation FENCE is held for the ENTIRE rebuild
# window — snapshot, join, shutdown, replacement discovery
# and readiness invalidation (Greptile review round 12).
# While /reload-mcp runs, a concurrent stream worker cannot
# CREATE a new discovery owner: not during teardown (the
# snapshot is COMPLETE, round 11), and not during the
# replacement build (no body registers servers concurrently
# with the reload's own discovery, and nothing gets
# invalidated out from under a fresh registration). The
# reload's own retry spawn skips the re-acquire
# (`_fence_held=True`) because threading.Lock is not
# reentrant; waiting turns are unaffected — they only wait
# on readiness events, never the fence.
with _MCP_RELOAD_FENCE:
if not _prepare_global_reload():
return (
"MCP reload aborted: a discovery run is still in "
f"progress after waiting {int(_MCP_READINESS_WAIT_CAP_S)}s. "
"Retry once it finishes."
)
shutdown_mcp_servers()
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

try:
from api.profiles import _resolve_hermes_home_override
_reload_override_available = _resolve_hermes_home_override() is not None
except Exception:
_reload_override_available = False

if _reload_override_available:
_readiness = _mcp_retry_discovery(
_canonical_readiness_key(''),
_reload_discover,
"mcp-reload",
_fence_held=True,
)
_reload_status = _mcp_wait_readiness(_readiness)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
else:
# Older agent: no context-local override — a background
# reload would read the process env while other streams
# mutate it. Run inline (pre-PR semantics), mirroring the
# stream worker's old-agent path (Greptile P1).
_reload_status = (
"completed" if _reload_discover() else "failed"
)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

# The global reload rebuilt the registry: every OTHER
# profile's readiness is stale. Remove those entries so each
# profile's next turn re-runs discovery instead of trusting a
# state whose servers were just shut down. Still inside the
# fence: a stream cannot spawn a fresh owner that would then
# be invalidated as stale (round 12).
_invalidate_mcp_readiness(except_key=_canonical_readiness_key(''))

with _lock:
connected_servers = set(_servers.keys())
Expand All @@ -291,10 +405,24 @@ def _run_reload_mcp_command() -> str:
lines.append(f"Removed: {', '.join(sorted(removed))}")

if connected_servers:
lines.append(f"{len(new_tools or [])} tool(s) available across {len(connected_servers)} server(s)")
_tool_count = 0
for _server_name in connected_servers:
try:
_tool_count += len(
getattr(_servers[_server_name], "_registered_tool_names", [])
or []
)
except Exception:
pass
lines.append(
f"{_tool_count} tool(s) available across {len(connected_servers)} server(s)"
)
else:
lines.append("No MCP servers connected")

if _reload_status == "failed":
lines.append("MCP discovery failed during reload — check the server logs")

if not reconnected and not added and not removed:
lines.append("Tooling state was already current")

Expand Down
Loading