alita-sdk 0.3.457__py3-none-any.whl → 0.3.465__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.
Potentially problematic release.
This version of alita-sdk might be problematic. Click here for more details.
- alita_sdk/cli/__init__.py +10 -0
- alita_sdk/cli/__main__.py +17 -0
- alita_sdk/cli/agent/__init__.py +0 -0
- alita_sdk/cli/agent/default.py +176 -0
- alita_sdk/cli/agent_executor.py +155 -0
- alita_sdk/cli/agent_loader.py +197 -0
- alita_sdk/cli/agent_ui.py +218 -0
- alita_sdk/cli/agents.py +1911 -0
- alita_sdk/cli/callbacks.py +576 -0
- alita_sdk/cli/cli.py +159 -0
- alita_sdk/cli/config.py +164 -0
- alita_sdk/cli/formatting.py +182 -0
- alita_sdk/cli/input_handler.py +256 -0
- alita_sdk/cli/mcp_loader.py +315 -0
- alita_sdk/cli/toolkit.py +330 -0
- alita_sdk/cli/toolkit_loader.py +55 -0
- alita_sdk/cli/tools/__init__.py +36 -0
- alita_sdk/cli/tools/approval.py +224 -0
- alita_sdk/cli/tools/filesystem.py +905 -0
- alita_sdk/cli/tools/planning.py +403 -0
- alita_sdk/cli/tools/terminal.py +280 -0
- alita_sdk/runtime/clients/client.py +16 -1
- alita_sdk/runtime/langchain/constants.py +2 -1
- alita_sdk/runtime/langchain/langraph_agent.py +17 -5
- alita_sdk/runtime/langchain/utils.py +1 -1
- alita_sdk/runtime/tools/function.py +17 -5
- alita_sdk/runtime/tools/llm.py +65 -7
- alita_sdk/tools/base_indexer_toolkit.py +54 -2
- alita_sdk/tools/qtest/api_wrapper.py +871 -32
- alita_sdk/tools/sharepoint/api_wrapper.py +22 -2
- alita_sdk/tools/sharepoint/authorization_helper.py +17 -1
- {alita_sdk-0.3.457.dist-info → alita_sdk-0.3.465.dist-info}/METADATA +145 -2
- {alita_sdk-0.3.457.dist-info → alita_sdk-0.3.465.dist-info}/RECORD +37 -15
- alita_sdk-0.3.465.dist-info/entry_points.txt +2 -0
- {alita_sdk-0.3.457.dist-info → alita_sdk-0.3.465.dist-info}/WHEEL +0 -0
- {alita_sdk-0.3.457.dist-info → alita_sdk-0.3.465.dist-info}/licenses/LICENSE +0 -0
- {alita_sdk-0.3.457.dist-info → alita_sdk-0.3.465.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Enhanced input handler with readline support.
|
|
3
|
+
|
|
4
|
+
Provides tab completion for commands, cursor movement, and input history.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import readline
|
|
8
|
+
import os
|
|
9
|
+
from typing import List, Optional
|
|
10
|
+
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.text import Text
|
|
13
|
+
|
|
14
|
+
console = Console()
|
|
15
|
+
|
|
16
|
+
# Available commands for autocompletion
|
|
17
|
+
CHAT_COMMANDS = [
|
|
18
|
+
'/help',
|
|
19
|
+
'/clear',
|
|
20
|
+
'/history',
|
|
21
|
+
'/save',
|
|
22
|
+
'/agent',
|
|
23
|
+
'/model',
|
|
24
|
+
'/mode',
|
|
25
|
+
'/mode always',
|
|
26
|
+
'/mode auto',
|
|
27
|
+
'/mode yolo',
|
|
28
|
+
'/dir',
|
|
29
|
+
'/session',
|
|
30
|
+
'/session list',
|
|
31
|
+
'/session resume',
|
|
32
|
+
'/add_mcp',
|
|
33
|
+
'/add_toolkit',
|
|
34
|
+
'exit',
|
|
35
|
+
'quit',
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ChatInputHandler:
|
|
40
|
+
"""
|
|
41
|
+
Enhanced input handler with readline support for chat sessions.
|
|
42
|
+
|
|
43
|
+
Features:
|
|
44
|
+
- Tab completion for slash commands
|
|
45
|
+
- Arrow key navigation through input history
|
|
46
|
+
- Cursor movement with left/right arrows
|
|
47
|
+
- Ctrl+A (start of line), Ctrl+E (end of line)
|
|
48
|
+
- Persistent command history within session
|
|
49
|
+
- Material UI-style input prompt
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self):
|
|
53
|
+
self._setup_readline()
|
|
54
|
+
self._input_history: List[str] = []
|
|
55
|
+
|
|
56
|
+
def _setup_readline(self):
|
|
57
|
+
"""Configure readline for enhanced input."""
|
|
58
|
+
# Set up tab completion
|
|
59
|
+
readline.set_completer(self._completer)
|
|
60
|
+
|
|
61
|
+
# Detect if we're using libedit (macOS) or GNU readline (Linux)
|
|
62
|
+
# libedit uses different syntax for parse_and_bind
|
|
63
|
+
if 'libedit' in readline.__doc__:
|
|
64
|
+
# macOS libedit syntax
|
|
65
|
+
readline.parse_and_bind('bind ^I rl_complete')
|
|
66
|
+
else:
|
|
67
|
+
# GNU readline syntax
|
|
68
|
+
readline.parse_and_bind('tab: complete')
|
|
69
|
+
|
|
70
|
+
# Enable emacs-style keybindings (Ctrl+A, Ctrl+E, etc.)
|
|
71
|
+
# This is usually the default on macOS/Linux
|
|
72
|
+
try:
|
|
73
|
+
if 'libedit' not in readline.__doc__:
|
|
74
|
+
readline.parse_and_bind('set editing-mode emacs')
|
|
75
|
+
except Exception:
|
|
76
|
+
pass # Some systems might not support this
|
|
77
|
+
|
|
78
|
+
# Set completion display style (GNU readline only)
|
|
79
|
+
try:
|
|
80
|
+
if 'libedit' not in readline.__doc__:
|
|
81
|
+
readline.parse_and_bind('set show-all-if-ambiguous on')
|
|
82
|
+
readline.parse_and_bind('set completion-ignore-case on')
|
|
83
|
+
except Exception:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
# Set delimiters for completion (space and common punctuation)
|
|
87
|
+
readline.set_completer_delims(' \t\n;')
|
|
88
|
+
|
|
89
|
+
def _completer(self, text: str, state: int) -> Optional[str]:
|
|
90
|
+
"""
|
|
91
|
+
Readline completer function for slash commands.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
text: The current text being completed
|
|
95
|
+
state: The state of completion (0 for first match, 1 for second, etc.)
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
The next matching command or None
|
|
99
|
+
"""
|
|
100
|
+
# Get the full line buffer
|
|
101
|
+
line = readline.get_line_buffer()
|
|
102
|
+
|
|
103
|
+
# Only complete at the start of the line or after whitespace
|
|
104
|
+
if line and not line.startswith('/') and text != line:
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
# Find matching commands
|
|
108
|
+
if text.startswith('/'):
|
|
109
|
+
matches = [cmd for cmd in CHAT_COMMANDS if cmd.startswith(text)]
|
|
110
|
+
elif text == '' and line == '':
|
|
111
|
+
# Show all commands on empty tab
|
|
112
|
+
matches = [cmd for cmd in CHAT_COMMANDS if cmd.startswith('/')]
|
|
113
|
+
else:
|
|
114
|
+
matches = [cmd for cmd in CHAT_COMMANDS if cmd.startswith(text)]
|
|
115
|
+
|
|
116
|
+
# Return the match at the given state
|
|
117
|
+
if state < len(matches):
|
|
118
|
+
return matches[state]
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
def get_input(self, prompt: str = "") -> str:
|
|
122
|
+
"""
|
|
123
|
+
Get user input with enhanced readline features.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
prompt: The prompt to display (note: for rich console, prompt is printed separately)
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
The user's input string
|
|
130
|
+
"""
|
|
131
|
+
try:
|
|
132
|
+
user_input = input(prompt)
|
|
133
|
+
|
|
134
|
+
# Add non-empty, non-duplicate inputs to history
|
|
135
|
+
if user_input.strip() and (not self._input_history or
|
|
136
|
+
self._input_history[-1] != user_input):
|
|
137
|
+
self._input_history.append(user_input)
|
|
138
|
+
readline.add_history(user_input)
|
|
139
|
+
|
|
140
|
+
return user_input
|
|
141
|
+
except (KeyboardInterrupt, EOFError):
|
|
142
|
+
raise
|
|
143
|
+
|
|
144
|
+
def clear_history(self):
|
|
145
|
+
"""Clear the input history."""
|
|
146
|
+
self._input_history.clear()
|
|
147
|
+
readline.clear_history()
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def history(self) -> List[str]:
|
|
151
|
+
"""Get the current input history."""
|
|
152
|
+
return self._input_history.copy()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# Global instance for use across the CLI
|
|
156
|
+
_input_handler: Optional[ChatInputHandler] = None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def get_input_handler() -> ChatInputHandler:
|
|
160
|
+
"""Get or create the global input handler instance."""
|
|
161
|
+
global _input_handler
|
|
162
|
+
if _input_handler is None:
|
|
163
|
+
_input_handler = ChatInputHandler()
|
|
164
|
+
return _input_handler
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def chat_input(prompt: str = "") -> str:
|
|
168
|
+
"""
|
|
169
|
+
Convenience function for getting chat input with enhanced features.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
prompt: The prompt to display
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
The user's input string
|
|
176
|
+
"""
|
|
177
|
+
return get_input_handler().get_input(prompt)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def styled_input() -> str:
|
|
181
|
+
"""
|
|
182
|
+
Get user input with a styled bordered prompt that works correctly with readline.
|
|
183
|
+
|
|
184
|
+
The prompt is passed directly to input() so readline can properly
|
|
185
|
+
handle cursor positioning and history navigation.
|
|
186
|
+
|
|
187
|
+
Returns:
|
|
188
|
+
The user's input string
|
|
189
|
+
"""
|
|
190
|
+
# Get terminal width for the border
|
|
191
|
+
try:
|
|
192
|
+
width = console.width - 2
|
|
193
|
+
except Exception:
|
|
194
|
+
width = 78
|
|
195
|
+
|
|
196
|
+
# Print the complete box frame first, then move cursor up to input line
|
|
197
|
+
console.print()
|
|
198
|
+
console.print(f"[dim]╭{'─' * width}╮[/dim]")
|
|
199
|
+
console.print(f"[dim]│[/dim]{' ' * width}[dim]│[/dim]")
|
|
200
|
+
console.print(f"[dim]╰{'─' * width}╯[/dim]")
|
|
201
|
+
|
|
202
|
+
# Move cursor up 2 lines and to position after "│ > "
|
|
203
|
+
# \033[2A = move up 2 lines, \033[4C = move right 4 columns
|
|
204
|
+
prompt = "\033[2A\033[2C > "
|
|
205
|
+
|
|
206
|
+
user_input = get_input_handler().get_input(prompt)
|
|
207
|
+
|
|
208
|
+
# Move cursor down to after the box
|
|
209
|
+
console.print()
|
|
210
|
+
|
|
211
|
+
return user_input
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def styled_selection_input(prompt_text: str = "Select") -> str:
|
|
215
|
+
"""
|
|
216
|
+
Get user selection input with a styled bordered prompt.
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
prompt_text: The prompt text to show (e.g., "Select model number")
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
The user's input string
|
|
223
|
+
"""
|
|
224
|
+
# Get terminal width for the border
|
|
225
|
+
try:
|
|
226
|
+
width = console.width - 2
|
|
227
|
+
except Exception:
|
|
228
|
+
width = 78
|
|
229
|
+
|
|
230
|
+
# Print the complete box frame first, then move cursor up to input line
|
|
231
|
+
console.print()
|
|
232
|
+
console.print(f"[dim]╭{'─' * width}╮[/dim]")
|
|
233
|
+
console.print(f"[dim]│[/dim]{' ' * width}[dim]│[/dim]")
|
|
234
|
+
console.print(f"[dim]╰{'─' * width}╯[/dim]")
|
|
235
|
+
|
|
236
|
+
# Move cursor up 2 lines and to position after "│"
|
|
237
|
+
# \033[2A = move up 2 lines, \033[2C = move right 2 columns
|
|
238
|
+
prompt = f"\033[2A\033[2C {prompt_text}: "
|
|
239
|
+
|
|
240
|
+
try:
|
|
241
|
+
user_input = input(prompt)
|
|
242
|
+
except (KeyboardInterrupt, EOFError):
|
|
243
|
+
console.print()
|
|
244
|
+
raise
|
|
245
|
+
|
|
246
|
+
# Move cursor down to after the box
|
|
247
|
+
console.print()
|
|
248
|
+
|
|
249
|
+
return user_input.strip()
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def print_input_prompt():
|
|
253
|
+
"""Print a clean, modern input prompt."""
|
|
254
|
+
# Simple clean prompt with > indicator
|
|
255
|
+
console.print() # Empty line for spacing
|
|
256
|
+
console.print("[bold cyan]>[/bold cyan] ", end="")
|
|
@@ -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, []
|