alita-sdk 0.3.459__py3-none-any.whl → 0.3.461__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- alita_sdk/cli/agent_executor.py +144 -0
- alita_sdk/cli/agent_loader.py +197 -0
- alita_sdk/cli/agent_ui.py +166 -0
- alita_sdk/cli/agents.py +278 -264
- alita_sdk/cli/callbacks.py +576 -0
- alita_sdk/cli/cli.py +3 -0
- alita_sdk/cli/config.py +23 -4
- alita_sdk/cli/mcp_loader.py +315 -0
- alita_sdk/cli/toolkit_loader.py +55 -0
- alita_sdk/cli/tools/__init__.py +9 -0
- alita_sdk/cli/tools/filesystem.py +905 -0
- alita_sdk/runtime/clients/client.py +1 -1
- alita_sdk/runtime/langchain/langraph_agent.py +1 -1
- alita_sdk/runtime/tools/function.py +15 -2
- alita_sdk/runtime/tools/llm.py +65 -7
- alita_sdk/tools/qtest/api_wrapper.py +84 -21
- {alita_sdk-0.3.459.dist-info → alita_sdk-0.3.461.dist-info}/METADATA +7 -7
- {alita_sdk-0.3.459.dist-info → alita_sdk-0.3.461.dist-info}/RECORD +22 -14
- {alita_sdk-0.3.459.dist-info → alita_sdk-0.3.461.dist-info}/WHEEL +0 -0
- {alita_sdk-0.3.459.dist-info → alita_sdk-0.3.461.dist-info}/entry_points.txt +0 -0
- {alita_sdk-0.3.459.dist-info → alita_sdk-0.3.461.dist-info}/licenses/LICENSE +0 -0
- {alita_sdk-0.3.459.dist-info → alita_sdk-0.3.461.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MCP (Model Context Protocol) server integration.
|
|
3
|
+
|
|
4
|
+
Handles loading MCP server configurations and connecting to MCP servers
|
|
5
|
+
using langchain-mcp-adapters to load tools with persistent sessions.
|
|
6
|
+
|
|
7
|
+
Requires: pip install langchain-mcp-adapters
|
|
8
|
+
Documentation: https://docs.langchain.com/oss/python/langchain/mcp
|
|
9
|
+
Issue Reference: https://github.com/langchain-ai/langchain-mcp-adapters/issues/178
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Dict, Any, List, Optional
|
|
16
|
+
from rich.console import Console
|
|
17
|
+
|
|
18
|
+
from .config import substitute_env_vars
|
|
19
|
+
|
|
20
|
+
console = Console()
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def load_mcp_config(file_path: str) -> Dict[str, Any]:
|
|
25
|
+
"""Load MCP configuration from JSON file (VSCode/Copilot format).
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
file_path: Path to mcp.json configuration file
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
Dictionary with mcpServers configuration, or empty dict if file doesn't exist
|
|
32
|
+
"""
|
|
33
|
+
path = Path(file_path)
|
|
34
|
+
|
|
35
|
+
if not path.exists():
|
|
36
|
+
# Gracefully handle missing file - MCP is optional
|
|
37
|
+
return {}
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
with open(path) as f:
|
|
41
|
+
content = f.read()
|
|
42
|
+
|
|
43
|
+
# Apply environment variable substitution
|
|
44
|
+
content = substitute_env_vars(content)
|
|
45
|
+
config = json.loads(content)
|
|
46
|
+
|
|
47
|
+
# Validate structure
|
|
48
|
+
if 'mcpServers' not in config:
|
|
49
|
+
console.print(f"[yellow]Warning: {file_path} missing 'mcpServers' key[/yellow]")
|
|
50
|
+
return {}
|
|
51
|
+
|
|
52
|
+
return config
|
|
53
|
+
except json.JSONDecodeError as e:
|
|
54
|
+
console.print(f"[red]Error parsing {file_path}:[/red] {e}")
|
|
55
|
+
return {}
|
|
56
|
+
except Exception as e:
|
|
57
|
+
console.print(f"[red]Error loading {file_path}:[/red] {e}")
|
|
58
|
+
return {}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_mcp_tools(agent_def: Dict[str, Any], mcp_config_path: str) -> List[Dict[str, Any]]:
|
|
62
|
+
"""Load MCP tools from agent definition with tool-level filtering.
|
|
63
|
+
|
|
64
|
+
This function creates MCP server configuration objects that will be processed
|
|
65
|
+
by the runtime layer using langchain-mcp-adapters to connect to MCP servers
|
|
66
|
+
and load their tools.
|
|
67
|
+
|
|
68
|
+
The actual connection happens in create_mcp_client() which uses:
|
|
69
|
+
- langchain_mcp_adapters.client.MultiServerMCPClient for connection
|
|
70
|
+
- langchain_mcp_adapters.tools.load_mcp_tools for tool loading
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
agent_def: Agent definition dictionary containing mcps list
|
|
74
|
+
mcp_config_path: Path to mcp.json configuration file (workspace-level)
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
List of MCP server configurations that will be used by MultiServerMCPClient
|
|
78
|
+
to connect to servers and load tools with filtering applied.
|
|
79
|
+
"""
|
|
80
|
+
import fnmatch
|
|
81
|
+
|
|
82
|
+
toolkit_configs = []
|
|
83
|
+
|
|
84
|
+
# Get MCP configuration
|
|
85
|
+
mcps = agent_def.get('mcps', [])
|
|
86
|
+
if not mcps:
|
|
87
|
+
return toolkit_configs
|
|
88
|
+
|
|
89
|
+
# Load mcp.json config file from workspace
|
|
90
|
+
mcp_config = load_mcp_config(mcp_config_path)
|
|
91
|
+
mcp_servers = mcp_config.get('mcpServers', {})
|
|
92
|
+
|
|
93
|
+
# Process each MCP entry
|
|
94
|
+
for mcp_entry in mcps:
|
|
95
|
+
# Handle both string and object formats
|
|
96
|
+
if isinstance(mcp_entry, str):
|
|
97
|
+
server_name = mcp_entry
|
|
98
|
+
agent_selected_tools = None
|
|
99
|
+
agent_excluded_tools = None
|
|
100
|
+
elif isinstance(mcp_entry, dict):
|
|
101
|
+
server_name = mcp_entry.get('name')
|
|
102
|
+
agent_selected_tools = mcp_entry.get('selected_tools')
|
|
103
|
+
agent_excluded_tools = mcp_entry.get('excluded_tools')
|
|
104
|
+
else:
|
|
105
|
+
console.print(f"[yellow]Warning: Invalid MCP entry format: {mcp_entry}[/yellow]")
|
|
106
|
+
continue
|
|
107
|
+
|
|
108
|
+
if not server_name:
|
|
109
|
+
console.print(f"[yellow]Warning: MCP entry missing 'name': {mcp_entry}[/yellow]")
|
|
110
|
+
continue
|
|
111
|
+
|
|
112
|
+
# Get server configuration
|
|
113
|
+
server_config = mcp_servers.get(server_name)
|
|
114
|
+
if not server_config:
|
|
115
|
+
console.print(f"[yellow]Warning: MCP server '{server_name}' not found in MCP configuration[/yellow]")
|
|
116
|
+
continue
|
|
117
|
+
|
|
118
|
+
# Determine tool selection (agent overrides server defaults)
|
|
119
|
+
server_selected_tools = server_config.get('selected_tools')
|
|
120
|
+
server_excluded_tools = server_config.get('excluded_tools')
|
|
121
|
+
|
|
122
|
+
# Agent overrides take precedence
|
|
123
|
+
final_selected_tools = agent_selected_tools if agent_selected_tools is not None else server_selected_tools
|
|
124
|
+
final_excluded_tools = agent_excluded_tools if agent_excluded_tools is not None else server_excluded_tools
|
|
125
|
+
|
|
126
|
+
# Get connection details
|
|
127
|
+
server_type = server_config.get('type') # VSCode format: "stdio" or "streamable_http"
|
|
128
|
+
server_url = server_config.get('url')
|
|
129
|
+
server_command = server_config.get('command')
|
|
130
|
+
server_args = server_config.get('args', [])
|
|
131
|
+
server_env = server_config.get('env', {})
|
|
132
|
+
stateful = server_config.get('stateful', False)
|
|
133
|
+
|
|
134
|
+
# Build MCP server config for langchain-mcp-adapters
|
|
135
|
+
# Support both VSCode format (type: "stdio") and our format (command: "...")
|
|
136
|
+
if server_type == 'stdio' or server_command:
|
|
137
|
+
# stdio transport (subprocess)
|
|
138
|
+
if not server_command:
|
|
139
|
+
console.print(f"[red]Error: MCP server '{server_name}' has type 'stdio' but no 'command'[/red]")
|
|
140
|
+
continue
|
|
141
|
+
|
|
142
|
+
console.print(f"[yellow]Note: MCP server '{server_name}' uses command/stdio connection[/yellow]")
|
|
143
|
+
mcp_server_config = {
|
|
144
|
+
'transport': 'stdio',
|
|
145
|
+
'command': server_command,
|
|
146
|
+
'args': server_args or []
|
|
147
|
+
}
|
|
148
|
+
elif server_type == 'streamable_http' or server_url:
|
|
149
|
+
# HTTP-based transport
|
|
150
|
+
if not server_url:
|
|
151
|
+
console.print(f"[red]Error: MCP server '{server_name}' has type 'streamable_http' but no 'url'[/red]")
|
|
152
|
+
continue
|
|
153
|
+
|
|
154
|
+
mcp_server_config = {
|
|
155
|
+
'transport': 'streamable_http',
|
|
156
|
+
'url': server_url
|
|
157
|
+
}
|
|
158
|
+
else:
|
|
159
|
+
console.print(f"[red]Error: MCP server '{server_name}' has neither 'type'/'url' nor 'command'[/red]")
|
|
160
|
+
continue
|
|
161
|
+
|
|
162
|
+
# Add environment variables if specified
|
|
163
|
+
if server_env:
|
|
164
|
+
mcp_server_config['env'] = server_env
|
|
165
|
+
|
|
166
|
+
# Wrap in toolkit config format
|
|
167
|
+
toolkit_config = {
|
|
168
|
+
'toolkit_type': 'mcp',
|
|
169
|
+
'name': server_name,
|
|
170
|
+
'mcp_server_config': mcp_server_config,
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
# Add tool filtering if specified
|
|
174
|
+
if final_selected_tools is not None:
|
|
175
|
+
toolkit_config['selected_tools'] = final_selected_tools
|
|
176
|
+
if final_excluded_tools is not None:
|
|
177
|
+
toolkit_config['excluded_tools'] = final_excluded_tools
|
|
178
|
+
|
|
179
|
+
toolkit_configs.append(toolkit_config)
|
|
180
|
+
|
|
181
|
+
# Display loaded tools info
|
|
182
|
+
if final_selected_tools:
|
|
183
|
+
tools_display = ', '.join(final_selected_tools)
|
|
184
|
+
console.print(f"✓ Loaded MCP server: [cyan]{server_name}[/cyan] (selected: {tools_display})")
|
|
185
|
+
elif final_excluded_tools:
|
|
186
|
+
console.print(f"✓ Loaded MCP server: [cyan]{server_name}[/cyan] (excluded: {', '.join(final_excluded_tools)})")
|
|
187
|
+
else:
|
|
188
|
+
console.print(f"✓ Loaded MCP server: [cyan]{server_name}[/cyan] (all tools)")
|
|
189
|
+
|
|
190
|
+
return toolkit_configs
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class MCPSessionManager:
|
|
194
|
+
"""Manages persistent MCP sessions for stateful tools like Playwright.
|
|
195
|
+
|
|
196
|
+
Holds MCP client and session context managers alive for the entire agent lifetime.
|
|
197
|
+
This is critical for stateful MCP servers that maintain state across tool calls
|
|
198
|
+
(e.g., Playwright browser sessions).
|
|
199
|
+
|
|
200
|
+
See: https://github.com/langchain-ai/langchain-mcp-adapters/issues/178
|
|
201
|
+
"""
|
|
202
|
+
def __init__(self):
|
|
203
|
+
self.client = None
|
|
204
|
+
self.sessions = {}
|
|
205
|
+
self._session_contexts = {}
|
|
206
|
+
|
|
207
|
+
def __del__(self):
|
|
208
|
+
"""Cleanup sessions when manager is garbage collected."""
|
|
209
|
+
# Best effort cleanup - sessions will be closed when process exits anyway
|
|
210
|
+
pass
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
async def load_mcp_tools_async(mcp_toolkit_configs: List[Dict[str, Any]]):
|
|
214
|
+
"""
|
|
215
|
+
Load actual MCP tools from servers with persistent sessions.
|
|
216
|
+
|
|
217
|
+
IMPORTANT: This function returns an MCPSessionManager that MUST be kept alive
|
|
218
|
+
for the entire agent session to maintain stateful MCP server state (e.g., browser).
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
mcp_toolkit_configs: List of MCP toolkit configurations with transport details
|
|
222
|
+
|
|
223
|
+
Returns:
|
|
224
|
+
Tuple of (session_manager, list_of_tools) where:
|
|
225
|
+
- session_manager: MCPSessionManager that holds client and persistent sessions
|
|
226
|
+
- list_of_tools: LangChain async tools from MCP that use persistent sessions
|
|
227
|
+
"""
|
|
228
|
+
if not mcp_toolkit_configs:
|
|
229
|
+
return None, []
|
|
230
|
+
|
|
231
|
+
try:
|
|
232
|
+
from langchain_mcp_adapters.client import MultiServerMCPClient
|
|
233
|
+
from langchain_mcp_adapters.tools import load_mcp_tools
|
|
234
|
+
except ImportError:
|
|
235
|
+
console.print("[yellow]Warning: langchain-mcp-adapters not installed. MCP tools will not be available.[/yellow]")
|
|
236
|
+
console.print("[yellow]Install with: pip install langchain-mcp-adapters[/yellow]")
|
|
237
|
+
return None, []
|
|
238
|
+
|
|
239
|
+
# Build server configs for MultiServerMCPClient
|
|
240
|
+
server_configs = {}
|
|
241
|
+
for config in mcp_toolkit_configs:
|
|
242
|
+
server_name = config.get('name', 'unknown')
|
|
243
|
+
mcp_server_config = config.get('mcp_server_config', {})
|
|
244
|
+
transport = mcp_server_config.get('transport', 'stdio')
|
|
245
|
+
|
|
246
|
+
if transport == 'stdio':
|
|
247
|
+
command = mcp_server_config.get('command')
|
|
248
|
+
args = mcp_server_config.get('args', [])
|
|
249
|
+
env = mcp_server_config.get('env')
|
|
250
|
+
|
|
251
|
+
# Ensure command is a string
|
|
252
|
+
if isinstance(command, list):
|
|
253
|
+
command = command[0] if command else None
|
|
254
|
+
|
|
255
|
+
# Build config dict - only include env if it's set
|
|
256
|
+
config_dict = {
|
|
257
|
+
'transport': 'stdio',
|
|
258
|
+
'command': command,
|
|
259
|
+
'args': args
|
|
260
|
+
}
|
|
261
|
+
if env:
|
|
262
|
+
config_dict['env'] = env
|
|
263
|
+
|
|
264
|
+
server_configs[server_name] = config_dict
|
|
265
|
+
console.print(f"[dim]MCP server {server_name}: {command} {' '.join(args)}[/dim]")
|
|
266
|
+
|
|
267
|
+
elif transport == 'streamable_http':
|
|
268
|
+
server_configs[server_name] = {
|
|
269
|
+
'transport': 'streamable_http',
|
|
270
|
+
'url': mcp_server_config.get('url'),
|
|
271
|
+
'headers': mcp_server_config.get('headers')
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if not server_configs:
|
|
275
|
+
return None, []
|
|
276
|
+
|
|
277
|
+
try:
|
|
278
|
+
# Create session manager to hold everything alive
|
|
279
|
+
manager = MCPSessionManager()
|
|
280
|
+
manager.client = MultiServerMCPClient(server_configs)
|
|
281
|
+
|
|
282
|
+
# Create PERSISTENT sessions for each server
|
|
283
|
+
# This keeps the MCP server subprocess and state alive for stateful tools
|
|
284
|
+
all_tools = []
|
|
285
|
+
|
|
286
|
+
for server_name in server_configs.keys():
|
|
287
|
+
# Enter the session context and keep it alive for entire agent lifetime
|
|
288
|
+
session_context = manager.client.session(server_name)
|
|
289
|
+
session = await session_context.__aenter__()
|
|
290
|
+
|
|
291
|
+
# Store both for cleanup and reference
|
|
292
|
+
manager.sessions[server_name] = session
|
|
293
|
+
manager._session_contexts[server_name] = session_context
|
|
294
|
+
|
|
295
|
+
# Load tools using the persistent session
|
|
296
|
+
tools = await load_mcp_tools(
|
|
297
|
+
session,
|
|
298
|
+
connection=manager.client.connections[server_name],
|
|
299
|
+
server_name=server_name
|
|
300
|
+
)
|
|
301
|
+
all_tools.extend(tools)
|
|
302
|
+
|
|
303
|
+
console.print(f"[dim]Created persistent session for {server_name}: {len(tools)} tools[/dim]")
|
|
304
|
+
|
|
305
|
+
console.print(f"✓ Loaded {len(all_tools)} MCP tools total from {len(mcp_toolkit_configs)} servers with persistent sessions")
|
|
306
|
+
|
|
307
|
+
return manager, all_tools
|
|
308
|
+
|
|
309
|
+
except ImportError:
|
|
310
|
+
# Already handled above
|
|
311
|
+
raise
|
|
312
|
+
except Exception as e:
|
|
313
|
+
logger.exception(f"Failed to create MCP client and sessions")
|
|
314
|
+
console.print(f"[red]Error: Failed to load MCP tools: {e}[/red]")
|
|
315
|
+
return None, []
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Toolkit configuration loading and management.
|
|
3
|
+
|
|
4
|
+
Handles loading toolkit configurations from JSON/YAML files.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import yaml
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Dict, Any, List
|
|
11
|
+
|
|
12
|
+
from .config import substitute_env_vars
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def load_toolkit_config(file_path: str) -> Dict[str, Any]:
|
|
16
|
+
"""Load toolkit configuration from JSON or YAML file with env var substitution."""
|
|
17
|
+
path = Path(file_path)
|
|
18
|
+
|
|
19
|
+
if not path.exists():
|
|
20
|
+
raise FileNotFoundError(f"Toolkit configuration not found: {file_path}")
|
|
21
|
+
|
|
22
|
+
with open(path) as f:
|
|
23
|
+
content = f.read()
|
|
24
|
+
|
|
25
|
+
# Apply environment variable substitution
|
|
26
|
+
content = substitute_env_vars(content)
|
|
27
|
+
|
|
28
|
+
# Parse based on file extension
|
|
29
|
+
if path.suffix in ['.yaml', '.yml']:
|
|
30
|
+
return yaml.safe_load(content)
|
|
31
|
+
else:
|
|
32
|
+
return json.loads(content)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_toolkit_configs(agent_def: Dict[str, Any], toolkit_config_paths: tuple) -> List[Dict[str, Any]]:
|
|
36
|
+
"""Load all toolkit configurations from agent definition and CLI options."""
|
|
37
|
+
toolkit_configs = []
|
|
38
|
+
|
|
39
|
+
# Load from agent definition if present
|
|
40
|
+
if 'toolkit_configs' in agent_def:
|
|
41
|
+
for tk_config in agent_def['toolkit_configs']:
|
|
42
|
+
if isinstance(tk_config, dict):
|
|
43
|
+
if 'file' in tk_config:
|
|
44
|
+
config = load_toolkit_config(tk_config['file'])
|
|
45
|
+
toolkit_configs.append(config)
|
|
46
|
+
elif 'config' in tk_config:
|
|
47
|
+
toolkit_configs.append(tk_config['config'])
|
|
48
|
+
|
|
49
|
+
# Load from CLI options
|
|
50
|
+
if toolkit_config_paths:
|
|
51
|
+
for config_path in toolkit_config_paths:
|
|
52
|
+
config = load_toolkit_config(config_path)
|
|
53
|
+
toolkit_configs.append(config)
|
|
54
|
+
|
|
55
|
+
return toolkit_configs
|