Skip to content

Commit 7adc499

Browse files
Fix silent toolset registration by emitting list_changed notifications (#491)
* fix(toolsets): emit tools/list_changed after enable/disable (closes #485) Server-side fix: enable_toolset and disable_toolset now send a ToolListChangedNotification so MCP clients refresh their cached tool registry. Correct per the MCP spec; the prior code documented this behavior but never implemented it. Note: the actual user-facing bug is an OpenCode client issue (anomalyco/opencode#48196) where local MCP servers silently fail to register tools during handshake. This fix will activate once OpenCode lands a client-side fix. * fix(toolsets): log failed list_changed send; deterministic notification tests Addresses Qodo review findings on #491: silent except-pass now logs a warning; asyncio.sleep polling replaced with an asyncio.Event wait. --------- Co-authored-by: John Dilts <[email protected]>
1 parent 5bbb934 commit 7adc499

2 files changed

Lines changed: 90 additions & 5 deletions

File tree

‎mcp_server/toolsets.py‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,25 @@
44
keep the *live* surface small. Every tool carries a category tag; `core` is always
55
on; other categories ship gated off and the agent turns them on with
66
`enable_toolset`. As the catalog grows toward full Godot coverage, the exposed set
7-
stays small. Built on FastMCP's tag-based `enable`/`disable` (which emit
8-
`tools/list_changed`).
7+
stays small. Built on FastMCP's tag-based `enable`/`disable`. After mutating the
8+
enabled set, ``enable_toolset`` / ``disable_toolset`` emit a
9+
``notifications/tools/list_changed`` so clients refresh their cached tool registry
10+
(issue #485).
911
1012
Some toolsets require a minimum Godot version because they rely on editor APIs
1113
added in later releases (e.g. ``input_map`` needs Godot 4.4+).
1214
"""
1315

1416
from __future__ import annotations
1517

18+
import logging
1619
import os
1720
import re
1821
from typing import Any
1922

2023
from fastmcp import Context, FastMCP
2124
from fastmcp.exceptions import ToolError
25+
from mcp_types import ToolListChangedNotification
2226
from pydantic import BaseModel
2327

2428
from mcp_server.bridge import Bridge
@@ -56,6 +60,8 @@
5660
from mcp_server.safety import READ_ONLY
5761
from mcp_server.toolset_middleware import ToolsetMiddleware
5862

63+
logger = logging.getLogger(__name__)
64+
5965
# Toggleable toolsets (category → agent-facing description). `core` is not here.
6066
TOOLSETS: dict[str, str] = {
6167
INSPECTION_TAG: "Read-only project, scene, and node inspection.",
@@ -311,9 +317,34 @@ async def enable_toolset(category: str, *, ctx: Context) -> ToolsetInfo:
311317
"""Expose a toolset's tools (e.g. "scene_edit") for this session. Returns the
312318
toolset's new state. Does not change anything in the Godot project.
313319
"""
314-
return await manager.enable(category, ctx=ctx)
320+
result = await manager.enable(category, ctx=ctx)
321+
await _notify_tools_changed(ctx)
322+
return result
315323

316324
@mcp.tool(meta=READ_ONLY, tags={CORE_TAG})
317325
async def disable_toolset(category: str, *, ctx: Context) -> ToolsetInfo:
318326
"""Hide a toolset's tools again to keep the active tool surface small."""
319-
return await manager.disable(category, ctx=ctx)
327+
result = await manager.disable(category, ctx=ctx)
328+
await _notify_tools_changed(ctx)
329+
return result
330+
331+
332+
async def _notify_tools_changed(ctx: Context) -> None:
333+
"""Emit ``notifications/tools/list_changed`` after the enabled set changes so
334+
clients refresh their cached tool registry (issue #485).
335+
336+
Fire-and-forget by design: the toggle already succeeded, so a delivery
337+
failure must not fail the tool call — but it is logged, never swallowed
338+
silently. Note: OpenCode has a known bug
339+
(https://github.com/anomalyco/opencode/issues/48196) where local MCP servers
340+
silently fail to register tools during handshake; this notification helps
341+
the moment that upstream issue is fixed.
342+
"""
343+
try:
344+
await ctx.send_notification(ToolListChangedNotification())
345+
except Exception:
346+
logger.warning(
347+
"tools/list_changed notification failed to send "
348+
"(client may have disconnected); toolset toggle already applied",
349+
exc_info=True,
350+
)

‎tests/contract/test_toolset_shared_state.py‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,12 @@
99

1010
from __future__ import annotations
1111

12+
import asyncio
13+
14+
import mcp_types
1215
import pytest
1316
from fastmcp import Client, FastMCP
17+
from fastmcp.client.messages import MessageHandler
1418

1519
from mcp_server.bridge import Bridge
1620
from mcp_server.config import ServerConfig
@@ -103,4 +107,54 @@ async def test_call_tool_blocked_when_not_enabled() -> None:
103107
)
104108
assert result.is_error
105109
msg = str(result.content).lower()
106-
assert "not enabled" in msg or "toolset" in msg
110+
assert "not enabled" in msg or "toolset" in msg
111+
112+
113+
# ---------------------------------------------------------------------------
114+
# 4. tools/list_changed notification (issue #485)
115+
# ---------------------------------------------------------------------------
116+
117+
118+
class _ToolListChangedRecorder(MessageHandler):
119+
"""Records ToolListChangedNotification receipts."""
120+
121+
def __init__(self) -> None:
122+
self.count = 0
123+
self.received = asyncio.Event()
124+
125+
async def on_tool_list_changed(
126+
self, message: mcp_types.ToolListChangedNotification
127+
) -> None:
128+
self.count += 1
129+
self.received.set()
130+
131+
132+
async def _wait_for(handler: _ToolListChangedRecorder, timeout: float = 5.0) -> None:
133+
"""Wait deterministically for the notification event (no sleep-waits)."""
134+
await asyncio.wait_for(handler.received.wait(), timeout=timeout)
135+
136+
137+
async def test_enable_toolset_sends_list_changed_notification() -> None:
138+
"""Enabling a toolset sends a tools/list_changed notification to the client."""
139+
server, _ = _build()
140+
handler = _ToolListChangedRecorder()
141+
async with Client(server, mode="legacy", message_handler=handler) as client:
142+
assert handler.count == 0
143+
await client.call_tool("godot_enable_toolset", {"category": "scene_edit"})
144+
await _wait_for(handler)
145+
assert handler.count >= 1
146+
147+
148+
async def test_disable_toolset_sends_list_changed_notification() -> None:
149+
"""Disabling a toolset sends a tools/list_changed notification to the client."""
150+
server, _ = _build()
151+
handler = _ToolListChangedRecorder()
152+
async with Client(server, mode="legacy", message_handler=handler) as client:
153+
await client.call_tool("godot_enable_toolset", {"category": "scene_edit"})
154+
await _wait_for(handler)
155+
handler.count = 0 # reset after enable
156+
handler.received.clear()
157+
await client.call_tool("godot_disable_toolset", {"category": "scene_edit"})
158+
await _wait_for(handler)
159+
assert handler.count >= 1
160+

0 commit comments

Comments
 (0)