-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_mcp_patch.py
More file actions
78 lines (68 loc) · 3.04 KB
/
simple_mcp_patch.py
File metadata and controls
78 lines (68 loc) · 3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
Simple and targeted patch for MCP client to handle the specific JSON-RPC validation error.
This focuses only on the call_tool method which is where the error occurs.
"""
import logging
from typing import Any
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def patch_mcp_call_tool_simple():
"""
Simple patch for the call_tool method to handle JSON-RPC validation errors.
"""
try:
from mcp.client.session import ClientSession
from mcp.types import CallToolResult, TextContent
# Store the original call_tool method
original_call_tool = ClientSession.call_tool
async def patched_call_tool(self, name: str, arguments: dict[str, Any] | None = None):
"""
Patched call_tool that handles JSON-RPC validation errors gracefully.
"""
try:
return await original_call_tool(self, name, arguments)
except Exception as e:
error_msg = str(e)
logger.error(f"MCP call_tool error for '{name}': {error_msg}")
# Handle the specific JSON-RPC validation error
if "validation errors for JSONRPCMessage" in error_msg:
error_content = TextContent(
type="text",
text=f"Tool '{name}' returned an invalid response from the server. This tool may not be properly configured or available."
)
elif "Invalid tool call and request method" in error_msg:
error_content = TextContent(
type="text",
text=f"Tool '{name}' is not available or the parameters are incorrect."
)
elif "Field required" in error_msg and "missing" in error_msg:
error_content = TextContent(
type="text",
text=f"Server configuration error for tool '{name}'. The server response is malformed."
)
else:
error_content = TextContent(
type="text",
text=f"Tool '{name}' encountered an error: {error_msg}"
)
return CallToolResult(
content=[error_content],
isError=True
)
# Apply the patch
ClientSession.call_tool = patched_call_tool
logger.info("Successfully patched MCP ClientSession.call_tool")
return True
except ImportError as e:
logger.error(f"Could not import MCP ClientSession: {e}")
return False
except Exception as e:
logger.error(f"Failed to patch MCP ClientSession.call_tool: {e}")
return False
if __name__ == "__main__":
success = patch_mcp_call_tool_simple()
if success:
print("✅ Simple MCP call_tool patching completed")
else:
print("❌ Simple MCP call_tool patching failed")