-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtool_manager.py
More file actions
394 lines (313 loc) · 14.3 KB
/
tool_manager.py
File metadata and controls
394 lines (313 loc) · 14.3 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
"""
Tool manager for MCI tools.
This module provides the ToolManager class that manages tool definitions
from an MCISchema, including retrieval, filtering, and execution.
"""
from pathlib import Path
from typing import Any
from .executors import ExecutorFactory
from .models import ExecutionResult, MCISchema, Tool
class ToolManagerError(Exception):
"""Exception raised for tool manager errors."""
pass
class ToolManager:
"""
Manager for MCI tool definitions.
Provides functionality to retrieve, filter, and execute tools from an
MCISchema. Handles input validation and dispatches execution to the
appropriate executor based on tool configuration.
"""
def __init__(self, schema: MCISchema, schema_file_path: str | None = None):
"""
Initialize the ToolManager with an MCISchema.
Args:
schema: MCISchema containing tool definitions
schema_file_path: Path to the schema file (for path validation context)
"""
self.schema = schema
# Create a mapping for fast tool lookup by name (excluding disabled tools)
# Handle case where tools might be None (when only toolsets are used)
tools_list = schema.tools if schema.tools is not None else []
self._tool_map: dict[str, Tool] = {
tool.name: tool for tool in tools_list if not tool.disabled
}
# Store schema file path for path validation
self._schema_file_path = schema_file_path
def get_tool(self, name: str) -> Tool | None:
"""
Retrieve a tool by name (case-sensitive), excluding disabled tools.
Args:
name: Name of the tool to retrieve
Returns:
Tool object if found and enabled, None otherwise
"""
return self._tool_map.get(name)
def list_tools(self) -> list[Tool]:
"""
List all available tools (excluding disabled tools).
Returns:
List of all enabled Tool objects in the schema
"""
tools_list = self.schema.tools if self.schema.tools is not None else []
return [tool for tool in tools_list if not tool.disabled]
def filter_tools(
self, only: list[str] | None = None, without: list[str] | None = None
) -> list[Tool]:
"""
Filter tools by inclusion/exclusion lists (excluding disabled tools).
If both 'only' and 'without' are provided, 'only' takes precedence
(i.e., only tools in the 'only' list but not in 'without' are returned).
Disabled tools are always excluded regardless of filters.
Args:
only: List of tool names to include (if None, all enabled tools are considered)
without: List of tool names to exclude (if None, no tools are excluded)
Returns:
Filtered list of Tool objects
"""
# Start with only enabled tools
tools_list = self.schema.tools if self.schema.tools is not None else []
tools = [tool for tool in tools_list if not tool.disabled]
# If 'only' is specified, filter to only those tools
if only is not None:
only_set = set(only)
tools = [tool for tool in tools if tool.name in only_set]
# If 'without' is specified, exclude those tools
if without is not None:
without_set = set(without)
tools = [tool for tool in tools if tool.name not in without_set]
return tools
def tags(self, tags: list[str]) -> list[Tool]:
"""
Filter tools to include only those with at least one matching tag (excluding disabled tools).
Returns tools that have at least one tag matching any tag in the provided list.
Uses OR logic: a tool is included if it has any of the specified tags.
Tags are matched case-sensitively and exactly as provided.
Args:
tags: List of tags to filter by
Returns:
Filtered list of Tool objects that have at least one matching tag
"""
# Start with only enabled tools
tools_list = self.schema.tools if self.schema.tools is not None else []
tools = [tool for tool in tools_list if not tool.disabled]
# Filter to tools that have at least one matching tag
# Empty tag list should return no tools
if not tags:
return []
tags_set = set(tags)
tools = [tool for tool in tools if any(tag in tags_set for tag in tool.tags)]
return tools
def withoutTags(self, tags: list[str]) -> list[Tool]:
"""
Filter tools to exclude those with any matching tag (excluding disabled tools).
Returns tools that do NOT have any tags matching the provided list.
Uses OR logic for exclusion: a tool is excluded if it has any of the specified tags.
Tags are matched case-sensitively and exactly as provided.
Args:
tags: List of tags to exclude
Returns:
Filtered list of Tool objects that do not have any of the specified tags
"""
# Start with only enabled tools
tools_list = self.schema.tools if self.schema.tools is not None else []
tools = [tool for tool in tools_list if not tool.disabled]
# Filter to tools that don't have any matching tags
# Empty tag list should return all tools
if not tags:
return tools
tags_set = set(tags)
tools = [tool for tool in tools if not any(tag in tags_set for tag in tool.tags)]
return tools
def toolsets(self, toolset_names: list[str]) -> list[Tool]:
"""
Filter tools to include only those from specified toolsets (excluding disabled tools).
Returns tools that were loaded from any of the specified toolsets.
Uses OR logic: a tool is included if it came from any of the specified toolsets.
Only tools that were registered by their toolset's schema-level filter are included.
Args:
toolset_names: List of toolset names to filter by
Returns:
Filtered list of Tool objects from the specified toolsets
"""
# Start with only enabled tools
tools_list = self.schema.tools if self.schema.tools is not None else []
tools = [tool for tool in tools_list if not tool.disabled]
# Filter to tools from specified toolsets
# Empty toolset list should return no tools
if not toolset_names:
return []
toolset_set = set(toolset_names)
tools = [
tool
for tool in tools
if tool.toolset_source is not None and tool.toolset_source in toolset_set
]
return tools
def execute(
self,
tool_name: str,
properties: dict[str, Any] | None = None,
env_vars: dict[str, Any] | None = None,
) -> ExecutionResult:
"""
Execute a tool by name with the provided properties.
Validates the tool exists, validates input properties against the tool's
input schema, and executes the tool using the appropriate executor.
Args:
tool_name: Name of the tool to execute
properties: Properties/parameters to pass to the tool (default: empty dict)
env_vars: Environment variables for template context (default: empty dict)
Returns:
ExecutionResult with success/error status and content
Raises:
ToolManagerError: If tool not found or properties validation fails
"""
# Default to empty dicts if None
if properties is None:
properties = {}
if env_vars is None:
env_vars = {}
# Check if tool exists
tool = self.get_tool(tool_name)
if tool is None:
raise ToolManagerError(f"Tool not found: {tool_name}")
# Delegate to execute_tool_model for actual execution
return self.execute_tool_model(tool=tool, properties=properties, env_vars=env_vars)
def execute_tool_model(
self,
tool: Tool,
properties: dict[str, Any] | None = None,
env_vars: dict[str, Any] | None = None,
) -> ExecutionResult:
"""
Execute a Tool model instance directly with the provided properties.
This method performs the actual execution logic used by both execute()
and executeSeparated(). It validates input properties, builds the execution
context, and dispatches to the appropriate executor.
Args:
tool: Tool model instance to execute
properties: Properties/parameters to pass to the tool (default: empty dict)
env_vars: Environment variables for template context (default: empty dict)
Returns:
ExecutionResult with success/error status and content
Raises:
ToolManagerError: If properties validation fails
"""
# Default to empty dicts if None
if properties is None:
properties = {}
if env_vars is None:
env_vars = {}
# Validate input schema if present
# Check both: not None (schema exists) and not empty dict (schema has content)
# This handles three cases: None (no schema), {} (empty schema), and {...} (schema with properties)
if tool.inputSchema is not None and tool.inputSchema:
self._validate_input_properties(tool, properties)
# Resolve properties with defaults applied and optional properties skipped
resolved_properties = self._resolve_properties_with_defaults(tool, properties)
else:
# No schema, use properties as-is
resolved_properties = properties
# Build context for execution
context: dict[str, Any] = {
"props": resolved_properties,
"env": env_vars,
"input": resolved_properties, # Alias for backward compatibility
}
# Build path validation context
path_context: dict[str, Any] | None = None
if self._schema_file_path:
from .path_validator import PathValidator
# Get context directory from schema file path
context_dir = Path(self._schema_file_path).parent
# Merge schema and tool settings (tool takes precedence)
enable_any_paths, directory_allow_list = PathValidator.merge_settings(
schema_enable_any_paths=self.schema.enableAnyPaths,
schema_directory_allow_list=self.schema.directoryAllowList,
tool_enable_any_paths=tool.enableAnyPaths,
tool_directory_allow_list=tool.directoryAllowList,
)
# Create path validator
path_context = {
"validator": PathValidator(
context_dir=context_dir,
enable_any_paths=enable_any_paths,
directory_allow_list=directory_allow_list,
)
}
# Add path context to execution context
context["path_validation"] = path_context
# Get the appropriate executor based on execution type
executor = ExecutorFactory.get_executor(
tool.execution.type, mcp_servers=self.schema.mcp_servers
)
# Execute the tool
result = executor.execute(tool.execution, context)
return result
def _validate_input_properties(self, tool: Tool, properties: dict[str, Any]) -> None:
"""
Validate properties against the tool's input schema.
Checks that all required properties are provided.
Args:
tool: Tool object with inputSchema
properties: Properties to validate
Raises:
ToolManagerError: If required properties are missing
"""
input_schema = tool.inputSchema
if not input_schema:
return
# Check for required properties
required = input_schema.get("required", [])
if required:
missing_props = [prop for prop in required if prop not in properties]
if missing_props:
raise ToolManagerError(
f"Tool '{tool.name}' requires properties: {', '.join(required)}. "
f"Missing: {', '.join(missing_props)}"
)
def _resolve_properties_with_defaults(
self, tool: Tool, properties: dict[str, Any]
) -> dict[str, Any]:
"""
Resolve properties with default values and skip optional properties.
For each property in the input schema:
- If provided in properties: use the provided value
- Else if has default value in schema: use the default
- Else if required: already validated, should not happen
- Else (optional without default): skip, don't include in resolved properties
This prevents template substitution errors for optional properties that
are not provided and have no default value.
Args:
tool: Tool object with inputSchema
properties: Properties provided by the caller
Returns:
Resolved properties dictionary with defaults applied and optional properties skipped
"""
input_schema = tool.inputSchema
if not input_schema:
return properties
# Get schema properties definition
schema_properties = input_schema.get("properties", {})
if not schema_properties:
# No properties defined in schema, return as-is
return properties
# Get required properties list
required = set(input_schema.get("required", []))
# Build resolved properties
resolved: dict[str, Any] = {}
# Process each property in the schema
for prop_name, prop_schema in schema_properties.items():
if prop_name in properties:
# Property was provided, use it
resolved[prop_name] = properties[prop_name]
elif "default" in prop_schema:
# Property not provided but has default, use default
resolved[prop_name] = prop_schema["default"]
elif prop_name in required:
# Required property not provided - this should have been caught by validation
# but we'll include it anyway to maintain consistency
# (validation should have raised an error before we get here)
pass
# else: optional property without default - skip it
return resolved