|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +from mcp import ServerResult, Tool |
| 4 | +from mcp.server.lowlevel import Server |
| 5 | +from mcp.types import CallToolRequest, CallToolResult, ListToolsRequest, TextContent |
| 6 | + |
| 7 | +from mcpcat.modules.tools import handle_report_missing |
| 8 | +from mcpcat.modules.tracing import record_trace |
| 9 | + |
| 10 | +from ...types import MCPCatData |
| 11 | +from ..logging import log_info, log_warning |
| 12 | +from ..session import capture_session_info |
| 13 | + |
| 14 | +"""Tool management and interception for MCPCat.""" |
| 15 | + |
| 16 | + |
| 17 | +def override_lowlevel_mcp_server(server: Server, data: MCPCatData) -> None: |
| 18 | + """Set up tool list and call handlers for FastMCP.""" |
| 19 | + from mcp.types import CallToolResult, ListToolsResult |
| 20 | + |
| 21 | + # Store original request handlers - we only need to intercept at the low-level |
| 22 | + original_call_tool_handler = server.request_handlers.get(CallToolRequest) |
| 23 | + original_list_tools_handler = server.request_handlers.get(ListToolsRequest) |
| 24 | + |
| 25 | + async def wrapped_list_tools_handler(request: ListToolsRequest) -> ServerResult: |
| 26 | + """Intercept list_tools requests to add MCPCat tools and modify existing ones.""" |
| 27 | + # Call the original handler to get the tools |
| 28 | + original_result = await original_list_tools_handler(request) |
| 29 | + if not original_result or not hasattr(original_result, 'root') or not hasattr(original_result.root, 'tools'): |
| 30 | + return original_result |
| 31 | + tools_list = original_result.root.tools |
| 32 | + |
| 33 | + # Add report_missing tool if enabled |
| 34 | + if data.options.enableReportMissing: |
| 35 | + report_missing_tool = Tool( |
| 36 | + name="report_missing", |
| 37 | + description="Report when a tool you need is missing from this server", |
| 38 | + inputSchema={ |
| 39 | + "type": "object", |
| 40 | + "properties": { |
| 41 | + "missing_tool": { |
| 42 | + "type": "string", |
| 43 | + "description": "Name of the missing tool" |
| 44 | + }, |
| 45 | + "description": { |
| 46 | + "type": "string", |
| 47 | + "description": "Description of what the tool should do" |
| 48 | + } |
| 49 | + }, |
| 50 | + "required": ["missing_tool", "description"] |
| 51 | + } |
| 52 | + ) |
| 53 | + tools_list.append(report_missing_tool) |
| 54 | + |
| 55 | + # Add context parameters to existing tools if enabled |
| 56 | + if data.options.enableToolCallContext: |
| 57 | + for tool in tools_list: |
| 58 | + if tool.name != "report_missing": # Don't modify our own tool |
| 59 | + if not tool.inputSchema: |
| 60 | + tool.inputSchema = { |
| 61 | + "type": "object", |
| 62 | + "properties": {}, |
| 63 | + "required": [] |
| 64 | + } |
| 65 | + |
| 66 | + # Add context property if it doesn't exist |
| 67 | + if "context" not in tool.inputSchema.get("properties", {}): |
| 68 | + if "properties" not in tool.inputSchema: |
| 69 | + tool.inputSchema["properties"] = {} |
| 70 | + |
| 71 | + tool.inputSchema["properties"]["context"] = { |
| 72 | + "type": "string", |
| 73 | + "description": "Describe why you are calling this tool and how it fits into your overall task" |
| 74 | + } |
| 75 | + |
| 76 | + # Add context to required array if it exists |
| 77 | + if isinstance(tool.inputSchema.get("required"), list): |
| 78 | + if "context" not in tool.inputSchema["required"]: |
| 79 | + tool.inputSchema["required"].append("context") |
| 80 | + else: |
| 81 | + tool.inputSchema["required"] = ["context"] |
| 82 | + |
| 83 | + return ServerResult(ListToolsResult(tools=tools_list)) |
| 84 | + |
| 85 | + async def wrapped_call_tool_handler(request: CallToolRequest) -> ServerResult: |
| 86 | + """Intercept call_tool requests to add MCPCat tracking and handle special tools.""" |
| 87 | + tool_name = request.params.name |
| 88 | + arguments = request.params.arguments or {} |
| 89 | + |
| 90 | + # Handle report_missing tool directly |
| 91 | + if tool_name == "report_missing": |
| 92 | + return await handle_report_missing(arguments, data) |
| 93 | + |
| 94 | + # Extract MCPCat context if enabled |
| 95 | + mcpcat_user_context = None |
| 96 | + if data.options.enableToolCallContext: |
| 97 | + mcpcat_user_context = arguments.pop("context", None) |
| 98 | + # Log warning if context is missing and tool is not report_missing |
| 99 | + if mcpcat_user_context is None and tool_name != "report_missing": |
| 100 | + log_warning("Missing context parameter", {"tool_name": tool_name}, data.options) |
| 101 | + |
| 102 | + # Get session info for tracking |
| 103 | + try: |
| 104 | + request_context = server.request_context |
| 105 | + session_id, user_id = await capture_session_info(server, arguments=arguments, request_context=request_context) |
| 106 | + except: |
| 107 | + request_context = None |
| 108 | + session_id, user_id = None, None |
| 109 | + |
| 110 | + # If tracing is enabled, wrap the call with timing and logging |
| 111 | + if data.options.enableTracing: |
| 112 | + import time |
| 113 | + start_time = time.time() |
| 114 | + |
| 115 | + try: |
| 116 | + # Call the original handler |
| 117 | + result = await original_call_tool_handler(request) |
| 118 | + duration = time.time() - start_time |
| 119 | + |
| 120 | + # Record the trace using existing infrastructure |
| 121 | + await record_trace( |
| 122 | + server=server, |
| 123 | + tool_name=tool_name, |
| 124 | + arguments=arguments, |
| 125 | + request_context=request_context, |
| 126 | + session_id=session_id, |
| 127 | + user_id=user_id, |
| 128 | + tool_result=result.model_dump() if result else None, |
| 129 | + duration=duration, |
| 130 | + mcpcat_context=mcpcat_user_context |
| 131 | + ) |
| 132 | + |
| 133 | + return result |
| 134 | + |
| 135 | + except Exception as e: |
| 136 | + duration = time.time() - start_time |
| 137 | + |
| 138 | + # Record the error trace |
| 139 | + await record_trace( |
| 140 | + server=server, |
| 141 | + tool_name=tool_name, |
| 142 | + arguments=arguments, |
| 143 | + request_context=request_context, |
| 144 | + session_id=session_id, |
| 145 | + user_id=user_id, |
| 146 | + tool_result=None, |
| 147 | + duration=duration, |
| 148 | + mcpcat_context=mcpcat_user_context, |
| 149 | + error=str(e) |
| 150 | + ) |
| 151 | + # Re-raise the exception |
| 152 | + raise |
| 153 | + else: |
| 154 | + # No tracing, just call the original handler |
| 155 | + return await original_call_tool_handler(request) |
| 156 | + |
| 157 | + # Replace only the low-level request handlers |
| 158 | + server.request_handlers[CallToolRequest] = wrapped_call_tool_handler |
| 159 | + server.request_handlers[ListToolsRequest] = wrapped_list_tools_handler |
| 160 | + |
0 commit comments