alita-sdk 0.3.423__py3-none-any.whl → 0.3.449__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.

@@ -0,0 +1,892 @@
1
+ """
2
+ MCP (Model Context Protocol) Toolkit for Alita SDK.
3
+ This toolkit enables connection to a single remote MCP server and exposes its tools.
4
+ Following MCP specification: https://modelcontextprotocol.io/specification/2025-06-18
5
+ """
6
+
7
+ import logging
8
+ import re
9
+ import requests
10
+ import asyncio
11
+ from typing import List, Optional, Any, Dict, Literal, ClassVar, Union
12
+
13
+ from langchain_core.tools import BaseToolkit, BaseTool
14
+ from pydantic import BaseModel, ConfigDict, Field
15
+
16
+ from ..tools.mcp_server_tool import McpServerTool
17
+ from ..tools.mcp_remote_tool import McpRemoteTool
18
+ from ..tools.mcp_inspect_tool import McpInspectTool
19
+ from ...tools.utils import TOOLKIT_SPLITTER, clean_string
20
+ from ..models.mcp_models import McpConnectionConfig
21
+ from ..utils.mcp_sse_client import McpSseClient
22
+ from ..utils.mcp_oauth import (
23
+ McpAuthorizationRequired,
24
+ canonical_resource,
25
+ extract_resource_metadata_url,
26
+ fetch_resource_metadata,
27
+ infer_authorization_servers_from_realm,
28
+ )
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ name = "mcp"
33
+
34
+ def safe_int(value, default):
35
+ """Convert value to int, handling string inputs."""
36
+ if value is None:
37
+ return default
38
+ try:
39
+ return int(value)
40
+ except (ValueError, TypeError):
41
+ logger.warning(f"Invalid integer value '{value}', using default {default}")
42
+ return default
43
+
44
+ def optimize_tool_name(prefix: str, tool_name: str, max_total_length: int = 64) -> str:
45
+ """
46
+ Optimize tool name to fit within max_total_length while preserving meaning.
47
+
48
+ Args:
49
+ prefix: The toolkit prefix (already cleaned)
50
+ tool_name: The original tool name
51
+ max_total_length: Maximum total length for the full tool name (default: 64)
52
+
53
+ Returns:
54
+ Optimized full tool name in format: prefix___tool_name
55
+ """
56
+ splitter = TOOLKIT_SPLITTER
57
+ splitter_len = len(splitter)
58
+ prefix_len = len(prefix)
59
+
60
+ # Calculate available space for tool name
61
+ available_space = max_total_length - prefix_len - splitter_len
62
+
63
+ if available_space <= 0:
64
+ logger.error(f"Prefix '{prefix}' is too long ({prefix_len} chars), cannot create valid tool name")
65
+ # Fallback: truncate prefix itself
66
+ prefix = prefix[:max_total_length - splitter_len - 10] # Leave 10 chars for tool name
67
+ available_space = max_total_length - len(prefix) - splitter_len
68
+
69
+ # If tool name fits, use it as-is
70
+ if len(tool_name) <= available_space:
71
+ return f'{prefix}{splitter}{tool_name}'
72
+
73
+ # Tool name is too long, need to optimize
74
+ logger.debug(f"Tool name '{tool_name}' is too long ({len(tool_name)} chars), optimizing to fit {available_space} chars")
75
+
76
+ # Split tool name into parts (handle camelCase, snake_case, and mixed)
77
+ # First, split by underscores and hyphens
78
+ parts = re.split(r'[_-]', tool_name)
79
+
80
+ # Further split camelCase within each part
81
+ all_parts = []
82
+ for part in parts:
83
+ # Insert underscore before uppercase letters (camelCase to snake_case)
84
+ snake_case_part = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', part)
85
+ all_parts.extend(snake_case_part.split('_'))
86
+
87
+ # Filter out empty parts
88
+ all_parts = [p for p in all_parts if p]
89
+
90
+ # Remove redundant prefix words (case-insensitive comparison)
91
+ # Only remove if prefix is meaningful (>= 3 chars) to avoid over-filtering
92
+ prefix_lower = prefix.lower()
93
+ filtered_parts = []
94
+ for part in all_parts:
95
+ part_lower = part.lower()
96
+ # Skip if this part contains the prefix or the prefix contains this part
97
+ # But only if both are meaningful (>= 3 chars)
98
+ should_remove = False
99
+ if len(prefix_lower) >= 3 and len(part_lower) >= 3:
100
+ if part_lower in prefix_lower or prefix_lower in part_lower:
101
+ should_remove = True
102
+ logger.debug(f"Removing redundant part '{part}' (matches prefix '{prefix}')")
103
+
104
+ if not should_remove:
105
+ filtered_parts.append(part)
106
+
107
+ # If we removed all parts, keep the original parts
108
+ if not filtered_parts:
109
+ filtered_parts = all_parts
110
+
111
+ # Reconstruct tool name with filtered parts
112
+ optimized_name = '_'.join(filtered_parts)
113
+
114
+ # If still too long, truncate intelligently
115
+ if len(optimized_name) > available_space:
116
+ # Strategy: Keep beginning and end, as they often contain the most important info
117
+ # For example: "projectalita_github_io_list_branches" -> "projectalita_list_branches"
118
+
119
+ # Try removing middle parts first
120
+ if len(filtered_parts) > 2:
121
+ # Keep first and last parts, remove middle
122
+ kept_parts = [filtered_parts[0], filtered_parts[-1]]
123
+ optimized_name = '_'.join(kept_parts)
124
+
125
+ # If still too long, add parts from the end until we run out of space
126
+ if len(optimized_name) <= available_space and len(filtered_parts) > 2:
127
+ for i in range(len(filtered_parts) - 2, 0, -1):
128
+ candidate = '_'.join([filtered_parts[0]] + filtered_parts[i:])
129
+ if len(candidate) <= available_space:
130
+ optimized_name = candidate
131
+ break
132
+
133
+ # If still too long, just truncate
134
+ if len(optimized_name) > available_space:
135
+ # Try to truncate at word boundary
136
+ truncated = optimized_name[:available_space]
137
+ last_underscore = truncated.rfind('_')
138
+ if last_underscore > available_space * 0.7: # Keep if we're not losing too much
139
+ optimized_name = truncated[:last_underscore]
140
+ else:
141
+ optimized_name = truncated
142
+
143
+ full_name = f'{prefix}{splitter}{optimized_name}'
144
+ logger.info(f"Optimized tool name: '{tool_name}' ({len(tool_name)} chars) -> '{optimized_name}' ({len(optimized_name)} chars), full: '{full_name}' ({len(full_name)} chars)")
145
+
146
+ return full_name
147
+
148
+ class McpToolkit(BaseToolkit):
149
+ """
150
+ MCP Toolkit for connecting to a single remote MCP server and exposing its tools.
151
+ Each toolkit instance represents one MCP server connection.
152
+ """
153
+
154
+ tools: List[BaseTool] = []
155
+ toolkit_name: Optional[str] = None
156
+
157
+ # Class variable (not Pydantic field) for tool name length limit
158
+ toolkit_max_length: ClassVar[int] = 0 # No limit for MCP tool names
159
+
160
+ def __getstate__(self):
161
+ """Custom serialization for pickle compatibility."""
162
+ state = self.__dict__.copy()
163
+ # The tools list should already be pickle-safe due to individual tool fixes
164
+ # Just return the state as-is since tools handle their own serialization
165
+ return state
166
+
167
+ def __setstate__(self, state):
168
+ """Custom deserialization for pickle compatibility."""
169
+ # Initialize Pydantic internal attributes if needed
170
+ if '__pydantic_fields_set__' not in state:
171
+ state['__pydantic_fields_set__'] = set(state.keys())
172
+ if '__pydantic_extra__' not in state:
173
+ state['__pydantic_extra__'] = None
174
+ if '__pydantic_private__' not in state:
175
+ state['__pydantic_private__'] = None
176
+
177
+ # Update object state
178
+ self.__dict__.update(state)
179
+
180
+ @staticmethod
181
+ def toolkit_config_schema() -> BaseModel:
182
+ """
183
+ Generate the configuration schema for MCP toolkit.
184
+ Following MCP specification for connection parameters.
185
+ """
186
+ from pydantic import create_model
187
+
188
+ return create_model(
189
+ 'mcp',
190
+ url=(
191
+ str,
192
+ Field(
193
+ description="MCP server HTTP URL",
194
+ json_schema_extra={
195
+ 'tooltip': 'HTTP URL for the MCP server (http:// or https://)',
196
+ 'example': 'https://your-mcp-server.com/mcp'
197
+ }
198
+ )
199
+ ),
200
+ headers=(
201
+ Optional[Dict[str, str]],
202
+ Field(
203
+ default=None,
204
+ description="HTTP headers for authentication and configuration",
205
+ json_schema_extra={
206
+ 'tooltip': 'HTTP headers to send with requests (e.g. Authorization)',
207
+ 'example': {'Authorization': 'Bearer your-api-token'}
208
+ }
209
+ )
210
+ ),
211
+ timeout=(
212
+ Union[int, str], # TODO: remove one I will figure out why UI sends str
213
+ Field(
214
+ default=300,
215
+ description="Request timeout in seconds (1-3600)"
216
+ )
217
+ ),
218
+ discovery_mode=(
219
+ Literal['static', 'dynamic', 'hybrid'],
220
+ Field(
221
+ default="dynamic",
222
+ description="Discovery mode",
223
+ json_schema_extra={
224
+ 'tooltip': 'static: use registry, dynamic: live discovery, hybrid: try dynamic first'
225
+ }
226
+ )
227
+ ),
228
+ discovery_interval=(
229
+ Union[int, str],
230
+ Field(
231
+ default=300,
232
+ description="Discovery interval in seconds (60-3600, for periodic discovery)"
233
+ )
234
+ ),
235
+ selected_tools=(
236
+ List[str],
237
+ Field(
238
+ default=[],
239
+ description="Specific tools to enable (empty = all tools)",
240
+ json_schema_extra={
241
+ 'tooltip': 'Leave empty to enable all tools from the MCP server'
242
+ }
243
+ )
244
+ ),
245
+ enable_caching=(
246
+ bool,
247
+ Field(
248
+ default=True,
249
+ description="Enable caching of tool schemas and responses"
250
+ )
251
+ ),
252
+ cache_ttl=(
253
+ Union[int, str],
254
+ Field(
255
+ default=300,
256
+ description="Cache TTL in seconds (60-3600)"
257
+ )
258
+ ),
259
+ __config__=ConfigDict(
260
+ json_schema_extra={
261
+ 'metadata': {
262
+ "label": "Remove MCP",
263
+ "icon_url": None,
264
+ "categories": ["other"],
265
+ "extra_categories": ["remote tools", "sse", "http"],
266
+ "description": "Connect to a remote Model Context Protocol (MCP) server via HTTP to access tools"
267
+ }
268
+ }
269
+ )
270
+ )
271
+
272
+ @classmethod
273
+ def get_toolkit(
274
+ cls,
275
+ url: str,
276
+ headers: Optional[Dict[str, str]] = None,
277
+ timeout: int = 60,
278
+ discovery_mode: str = "hybrid",
279
+ discovery_interval: int = 300,
280
+ selected_tools: List[str] = None,
281
+ enable_caching: bool = True,
282
+ cache_ttl: int = 300,
283
+ toolkit_name: str = None,
284
+ client = None,
285
+ **kwargs
286
+ ) -> 'McpToolkit':
287
+ """
288
+ Create an MCP toolkit instance for a single MCP server.
289
+
290
+ When valid connection configuration (url + headers) is provided, the toolkit will:
291
+ 1. Immediately perform live discovery from the MCP server
292
+ 2. Create BaseTool instances for all discovered tools with complete schemas
293
+ 3. Include an inspection tool for server exploration
294
+ 4. Return all tools via get_tools() method
295
+
296
+ Args:
297
+ url: MCP server HTTP URL
298
+ headers: HTTP headers for authentication
299
+ timeout: Request timeout in seconds
300
+ discovery_mode: Discovery mode ('static', 'dynamic', 'hybrid')
301
+ discovery_interval: Discovery interval in seconds (for periodic discovery)
302
+ selected_tools: List of specific tools to enable (empty = all tools)
303
+ enable_caching: Whether to enable caching
304
+ cache_ttl: Cache TTL in seconds
305
+ toolkit_name: Toolkit name/identifier and prefix for tools
306
+ client: Alita client for MCP communication
307
+ **kwargs: Additional configuration options
308
+
309
+ Returns:
310
+ Configured McpToolkit instance with all available tools discovered
311
+ """
312
+ if selected_tools is None:
313
+ selected_tools = []
314
+
315
+ if not toolkit_name:
316
+ raise ValueError("toolkit_name is required")
317
+
318
+ # Convert numeric parameters that may come as strings from UI
319
+ timeout = safe_int(timeout, 60)
320
+ discovery_interval = safe_int(discovery_interval, 300)
321
+ cache_ttl = safe_int(cache_ttl, 300)
322
+
323
+ logger.info(f"Creating MCP toolkit: {toolkit_name}")
324
+
325
+ # Parse headers if they're provided as a JSON string
326
+ parsed_headers = headers
327
+ if isinstance(headers, str) and headers.strip():
328
+ try:
329
+ import json
330
+ logger.debug(f"Raw headers string length: {len(headers)} chars")
331
+ logger.debug(f"Raw headers string (first 100 chars): {headers[:100]}")
332
+ logger.debug(f"Raw headers string (last 100 chars): {headers[-100:]}")
333
+ parsed_headers = json.loads(headers)
334
+ logger.info(f"Parsed headers from JSON string successfully")
335
+ logger.debug(f"Parsed headers: {parsed_headers}")
336
+ except json.JSONDecodeError as e:
337
+ logger.error(f"Failed to parse headers JSON: {e}")
338
+ logger.error(f"Headers string length: {len(headers)}")
339
+ logger.error(f"Headers string content: {repr(headers)}")
340
+ raise ValueError(f"Invalid headers JSON format: {e}")
341
+ elif headers is not None and not isinstance(headers, dict):
342
+ logger.error(f"Headers must be a dictionary or JSON string, got: {type(headers)}")
343
+ raise ValueError(f"Headers must be a dictionary or JSON string, got: {type(headers)}")
344
+
345
+ # Extract session_id from kwargs if provided
346
+ session_id = kwargs.get('session_id')
347
+ if session_id:
348
+ logger.info(f"[MCP Session] Using provided session ID for toolkit '{toolkit_name}': {session_id}")
349
+
350
+ # Create MCP connection configuration
351
+ try:
352
+ connection_config = McpConnectionConfig(url=url, headers=parsed_headers, session_id=session_id)
353
+ except Exception as e:
354
+ logger.error(f"Invalid MCP connection configuration: {e}")
355
+ raise ValueError(f"Invalid MCP connection configuration: {e}")
356
+
357
+ # Create toolkit instance
358
+ toolkit = cls(toolkit_name=toolkit_name)
359
+
360
+ # Generate tools from the MCP server
361
+ toolkit.tools = cls._create_tools_from_server(
362
+ toolkit_name=toolkit_name,
363
+ connection_config=connection_config,
364
+ timeout=timeout,
365
+ selected_tools=selected_tools,
366
+ client=client,
367
+ discovery_mode=discovery_mode
368
+ )
369
+
370
+ return toolkit
371
+
372
+ @classmethod
373
+ def _create_tools_from_server(
374
+ cls,
375
+ toolkit_name: str,
376
+ connection_config: McpConnectionConfig,
377
+ timeout: int,
378
+ selected_tools: List[str],
379
+ client,
380
+ discovery_mode: str = "dynamic"
381
+ ) -> List[BaseTool]:
382
+ """
383
+ Create tools from a single MCP server. Always performs live discovery when connection config is provided.
384
+ """
385
+ tools = []
386
+
387
+ # First, try direct HTTP discovery since we have valid connection config
388
+ try:
389
+ logger.info(f"Discovering tools from MCP toolkit '{toolkit_name}' at {connection_config.url}")
390
+
391
+ # Use synchronous HTTP discovery for toolkit initialization
392
+ tool_metadata_list, session_id = cls._discover_tools_sync(
393
+ toolkit_name=toolkit_name,
394
+ connection_config=connection_config,
395
+ timeout=timeout
396
+ )
397
+
398
+ # Filter tools if specific ones are selected
399
+ selected_tools_lower = [tool.lower() for tool in selected_tools] if selected_tools else []
400
+ if selected_tools_lower:
401
+ tool_metadata_list = [
402
+ tool for tool in tool_metadata_list
403
+ if tool.get('name', '').lower() in selected_tools_lower
404
+ ]
405
+
406
+ # Create BaseTool instances from discovered metadata
407
+ # Use session_id from frontend (passed via connection_config)
408
+ if session_id:
409
+ logger.info(f"[MCP Session] Using session_id from frontend: {session_id}")
410
+
411
+ for tool_metadata in tool_metadata_list:
412
+ server_tool = cls._create_tool_from_dict(
413
+ tool_dict=tool_metadata,
414
+ toolkit_name=toolkit_name,
415
+ connection_config=connection_config,
416
+ timeout=timeout,
417
+ client=client,
418
+ session_id=session_id # Use session from discovery
419
+ )
420
+
421
+ if server_tool:
422
+ tools.append(server_tool)
423
+
424
+ logger.info(f"Successfully created {len(tools)} MCP tools from toolkit '{toolkit_name}' via direct discovery")
425
+
426
+ except Exception as e:
427
+ logger.error(f"Direct discovery failed for MCP toolkit '{toolkit_name}': {e}", exc_info=True)
428
+ logger.error(f"Discovery error details - URL: {connection_config.url}, Timeout: {timeout}s")
429
+
430
+ # Fallback to static mode if available and not already static
431
+ if isinstance(e, McpAuthorizationRequired):
432
+ # Authorization is required; surface upstream so the caller can prompt the user
433
+ raise
434
+ if client and discovery_mode != "static":
435
+ logger.info(f"Falling back to static discovery for toolkit '{toolkit_name}'")
436
+ tools = cls._create_tools_static(toolkit_name, selected_tools, timeout, client)
437
+ else:
438
+ logger.warning(f"No fallback available for toolkit '{toolkit_name}' - returning empty tools list")
439
+
440
+ # Don't add inspection tool to agent - it's only for internal use by toolkit
441
+ # inspection_tool = cls._create_inspection_tool(
442
+ # toolkit_name=toolkit_name,
443
+ # connection_config=connection_config
444
+ # )
445
+ # if inspection_tool:
446
+ # tools.append(inspection_tool)
447
+ # logger.info(f"Added MCP inspection tool for toolkit '{toolkit_name}'")
448
+
449
+ # Log final tool count before returning
450
+ logger.info(f"MCP toolkit '{toolkit_name}' will provide {len(tools)} tools to agent")
451
+ if len(tools) == 0:
452
+ logger.warning(f"MCP toolkit '{toolkit_name}' has no tools - discovery may have failed")
453
+
454
+ return tools
455
+
456
+ @classmethod
457
+ def _discover_tools_sync(
458
+ cls,
459
+ toolkit_name: str,
460
+ connection_config: McpConnectionConfig,
461
+ timeout: int
462
+ ) -> List[Dict[str, Any]]:
463
+ """
464
+ Discover tools and prompts from MCP server using SSE client.
465
+ Returns list of tool/prompt dictionaries with name, description, and inputSchema.
466
+ Prompts are converted to tools that can be invoked.
467
+ """
468
+ session_id = connection_config.session_id
469
+
470
+ if not session_id:
471
+ logger.warning(f"[MCP Session] No session_id provided for '{toolkit_name}' - server may require it")
472
+ logger.warning(f"[MCP Session] Frontend should generate a UUID and include it with mcp_tokens")
473
+
474
+ # Run async discovery in sync context
475
+ try:
476
+ all_tools = asyncio.run(
477
+ cls._discover_tools_async(
478
+ toolkit_name=toolkit_name,
479
+ connection_config=connection_config,
480
+ timeout=timeout
481
+ )
482
+ )
483
+ return all_tools, session_id
484
+ except Exception as e:
485
+ logger.error(f"[MCP SSE] Discovery failed for '{toolkit_name}': {e}")
486
+ raise
487
+
488
+ @classmethod
489
+ async def _discover_tools_async(
490
+ cls,
491
+ toolkit_name: str,
492
+ connection_config: McpConnectionConfig,
493
+ timeout: int
494
+ ) -> List[Dict[str, Any]]:
495
+ """
496
+ Async implementation of tool discovery using SSE client.
497
+ """
498
+ all_tools = []
499
+ session_id = connection_config.session_id
500
+
501
+ if not session_id:
502
+ logger.error(f"[MCP SSE] session_id is required for SSE servers")
503
+ raise ValueError("session_id is required. Frontend must generate UUID.")
504
+
505
+ logger.info(f"[MCP SSE] Discovering from {connection_config.url} with session {session_id}")
506
+
507
+ # Prepare headers
508
+ headers = {}
509
+ if connection_config.headers:
510
+ headers.update(connection_config.headers)
511
+
512
+ # Create SSE client
513
+ client = McpSseClient(
514
+ url=connection_config.url,
515
+ session_id=session_id,
516
+ headers=headers,
517
+ timeout=timeout
518
+ )
519
+
520
+ # Initialize MCP session
521
+ await client.initialize()
522
+ logger.info(f"[MCP SSE] Session initialized for '{toolkit_name}'")
523
+
524
+ # Discover tools
525
+ tools = await client.list_tools()
526
+ all_tools.extend(tools)
527
+ logger.info(f"[MCP SSE] Discovered {len(tools)} tools from '{toolkit_name}'")
528
+
529
+ # Discover prompts
530
+ try:
531
+ prompts = await client.list_prompts()
532
+ # Convert prompts to tool format
533
+ for prompt in prompts:
534
+ prompt_tool = {
535
+ "name": f"prompt_{prompt.get('name', 'unnamed')}",
536
+ "description": prompt.get('description', f"Execute prompt: {prompt.get('name')}"),
537
+ "inputSchema": {
538
+ "type": "object",
539
+ "properties": {
540
+ "arguments": {
541
+ "type": "object",
542
+ "description": "Arguments for the prompt template",
543
+ "properties": {
544
+ arg.get("name"): {
545
+ "type": "string",
546
+ "description": arg.get("description", ""),
547
+ "required": arg.get("required", False)
548
+ }
549
+ for arg in prompt.get("arguments", [])
550
+ }
551
+ }
552
+ }
553
+ },
554
+ "_mcp_type": "prompt",
555
+ "_mcp_prompt_name": prompt.get('name')
556
+ }
557
+ all_tools.append(prompt_tool)
558
+ logger.info(f"[MCP SSE] Discovered {len(prompts)} prompts from '{toolkit_name}'")
559
+ except Exception as e:
560
+ logger.warning(f"[MCP SSE] Failed to discover prompts: {e}")
561
+
562
+ logger.info(f"[MCP SSE] Total discovered {len(all_tools)} items from '{toolkit_name}'")
563
+ return all_tools
564
+
565
+ @classmethod
566
+ def _create_tool_from_dict(
567
+ cls,
568
+ tool_dict: Dict[str, Any],
569
+ toolkit_name: str,
570
+ connection_config: McpConnectionConfig,
571
+ timeout: int,
572
+ client,
573
+ session_id: Optional[str] = None
574
+ ) -> Optional[BaseTool]:
575
+ """Create a BaseTool from a tool/prompt dictionary (from direct HTTP discovery)."""
576
+ try:
577
+ # Store toolkit_max_length in local variable to avoid contextual access issues
578
+ max_length_value = cls.toolkit_max_length
579
+
580
+ # Clean toolkit name for prefixing
581
+ clean_prefix = clean_string(toolkit_name, max_length_value)
582
+
583
+ # Optimize tool name to fit within 64 character limit
584
+ full_tool_name = optimize_tool_name(clean_prefix, tool_dict.get("name", "unknown"))
585
+
586
+ # Check if this is a prompt (converted to tool)
587
+ is_prompt = tool_dict.get("_mcp_type") == "prompt"
588
+ item_type = "prompt" if is_prompt else "tool"
589
+
590
+ # Build description and ensure it doesn't exceed 1000 characters
591
+ description = f"MCP {item_type} '{tool_dict.get('name')}' from toolkit '{toolkit_name}': {tool_dict.get('description', '')}"
592
+ if len(description) > 1000:
593
+ description = description[:997] + "..."
594
+ logger.debug(f"Trimmed description for tool '{tool_dict.get('name')}' from {len(description)} to 1000 chars")
595
+
596
+ # Use McpRemoteTool for remote MCP servers (HTTP/SSE)
597
+ return McpRemoteTool(
598
+ name=full_tool_name,
599
+ description=description,
600
+ args_schema=McpServerTool.create_pydantic_model_from_schema(
601
+ tool_dict.get("inputSchema", {})
602
+ ),
603
+ client=client,
604
+ server=toolkit_name,
605
+ server_url=connection_config.url,
606
+ server_headers=connection_config.headers,
607
+ tool_timeout_sec=timeout,
608
+ is_prompt=is_prompt,
609
+ prompt_name=tool_dict.get("_mcp_prompt_name") if is_prompt else None,
610
+ original_tool_name=tool_dict.get('name'), # Store original name for MCP server invocation
611
+ session_id=session_id # Pass session ID for stateful SSE servers
612
+ )
613
+ except Exception as e:
614
+ logger.error(f"Failed to create MCP tool '{tool_dict.get('name')}' from toolkit '{toolkit_name}': {e}")
615
+ return None
616
+
617
+ @classmethod
618
+ def _create_tools_static(
619
+ cls,
620
+ toolkit_name: str,
621
+ selected_tools: List[str],
622
+ timeout: int,
623
+ client
624
+ ) -> List[BaseTool]:
625
+ """Fallback static tool creation using the original method."""
626
+ tools = []
627
+
628
+ if not client or not hasattr(client, 'get_mcp_toolkits'):
629
+ logger.warning("Alita client does not support MCP toolkit discovery")
630
+ return tools
631
+
632
+ try:
633
+ all_toolkits = client.get_mcp_toolkits()
634
+ server_toolkit = next((tk for tk in all_toolkits if tk.get('name') == toolkit_name), None)
635
+
636
+ if not server_toolkit:
637
+ logger.warning(f"MCP toolkit '{toolkit_name}' not found in available toolkits")
638
+ return tools
639
+
640
+ # Extract tools from the toolkit
641
+ available_tools = server_toolkit.get('tools', [])
642
+ selected_tools_lower = [tool.lower() for tool in selected_tools] if selected_tools else []
643
+
644
+ for available_tool in available_tools:
645
+ tool_name = available_tool.get("name", "").lower()
646
+
647
+ # Filter tools if specific tools are selected
648
+ if selected_tools_lower and tool_name not in selected_tools_lower:
649
+ continue
650
+
651
+ # Create the tool
652
+ server_tool = cls._create_single_tool(
653
+ toolkit_name=toolkit_name,
654
+ available_tool=available_tool,
655
+ timeout=timeout,
656
+ client=client
657
+ )
658
+
659
+ if server_tool:
660
+ tools.append(server_tool)
661
+
662
+ logger.info(f"Successfully created {len(tools)} MCP tools from toolkit '{toolkit_name}' using static mode")
663
+
664
+ except Exception as e:
665
+ logger.error(f"Error in static tool creation: {e}")
666
+
667
+ # Always add the inspection tool (not subject to selected_tools filtering)
668
+ # For static mode, we need to create a basic connection config from the server info
669
+ try:
670
+ # We don't have full connection config in static mode, so create a basic one
671
+ # The inspection tool will work as long as the server is accessible
672
+ inspection_tool = McpInspectTool(
673
+ name=f"{clean_string(toolkit_name, 50)}{TOOLKIT_SPLITTER}mcp_inspect",
674
+ server_name=toolkit_name,
675
+ server_url="", # Will be populated by the client if available
676
+ description=f"Inspect available tools, prompts, and resources from MCP toolkit '{toolkit_name}'"
677
+ )
678
+ tools.append(inspection_tool)
679
+ logger.info(f"Added MCP inspection tool for toolkit '{toolkit_name}' (static mode)")
680
+ except Exception as e:
681
+ logger.warning(f"Failed to create inspection tool for {toolkit_name}: {e}")
682
+
683
+ return tools
684
+
685
+ @classmethod
686
+ def _create_tool_from_metadata(
687
+ cls,
688
+ tool_metadata,
689
+ toolkit_name: str,
690
+ timeout: int,
691
+ client
692
+ ) -> Optional[BaseTool]:
693
+ """Create a BaseTool from discovered metadata."""
694
+ try:
695
+ # Store toolkit_max_length in local variable to avoid contextual access issues
696
+ max_length_value = cls.toolkit_max_length
697
+
698
+ # Clean server name for prefixing (use tool_metadata.server instead of toolkit_name)
699
+ clean_prefix = clean_string(tool_metadata.server, max_length_value)
700
+ # Optimize tool name to fit within 64 character limit
701
+ full_tool_name = optimize_tool_name(clean_prefix, tool_metadata.name)
702
+
703
+ # Build description and ensure it doesn't exceed 1000 characters
704
+ description = f"MCP tool '{tool_metadata.name}' from server '{tool_metadata.server}': {tool_metadata.description}"
705
+ if len(description) > 1000:
706
+ description = description[:997] + "..."
707
+ logger.debug(f"Trimmed description for tool '{tool_metadata.name}' from {len(description)} to 1000 chars")
708
+
709
+ return McpServerTool(
710
+ name=full_tool_name,
711
+ description=description,
712
+ args_schema=McpServerTool.create_pydantic_model_from_schema(tool_metadata.input_schema),
713
+ client=client,
714
+ server=tool_metadata.server,
715
+ tool_timeout_sec=timeout
716
+ )
717
+ except Exception as e:
718
+ logger.error(f"Failed to create MCP tool '{tool_metadata.name}' from server '{tool_metadata.server}': {e}")
719
+ return None
720
+
721
+ @classmethod
722
+ def _create_single_tool(
723
+ cls,
724
+ toolkit_name: str,
725
+ available_tool: Dict[str, Any],
726
+ timeout: int,
727
+ client
728
+ ) -> Optional[BaseTool]:
729
+ """Create a single MCP tool."""
730
+ try:
731
+ # Store toolkit_max_length in local variable to avoid contextual access issues
732
+ max_length_value = cls.toolkit_max_length
733
+
734
+ # Clean toolkit name for prefixing
735
+ clean_prefix = clean_string(toolkit_name, max_length_value)
736
+
737
+ # Optimize tool name to fit within 64 character limit
738
+ full_tool_name = optimize_tool_name(clean_prefix, available_tool["name"])
739
+
740
+ # Build description and ensure it doesn't exceed 1000 characters
741
+ description = f"MCP tool '{available_tool['name']}' from toolkit '{toolkit_name}': {available_tool.get('description', '')}"
742
+ if len(description) > 1000:
743
+ description = description[:997] + "..."
744
+ logger.debug(f"Trimmed description for tool '{available_tool['name']}' from {len(description)} to 1000 chars")
745
+
746
+ return McpServerTool(
747
+ name=full_tool_name,
748
+ description=description,
749
+ args_schema=McpServerTool.create_pydantic_model_from_schema(
750
+ available_tool.get("inputSchema", {})
751
+ ),
752
+ client=client,
753
+ server=toolkit_name,
754
+ tool_timeout_sec=timeout
755
+ )
756
+ except Exception as e:
757
+ logger.error(f"Failed to create MCP tool '{available_tool.get('name')}' from toolkit '{toolkit_name}': {e}")
758
+ return None
759
+
760
+ @classmethod
761
+ def _create_inspection_tool(
762
+ cls,
763
+ toolkit_name: str,
764
+ connection_config: McpConnectionConfig
765
+ ) -> Optional[BaseTool]:
766
+ """Create the inspection tool for the MCP toolkit."""
767
+ try:
768
+ # Store toolkit_max_length in local variable to avoid contextual access issues
769
+ max_length_value = cls.toolkit_max_length
770
+
771
+ # Clean toolkit name for prefixing
772
+ clean_prefix = clean_string(toolkit_name, max_length_value)
773
+
774
+ full_tool_name = f'{clean_prefix}{TOOLKIT_SPLITTER}mcp_inspect'
775
+
776
+ return McpInspectTool(
777
+ name=full_tool_name,
778
+ server_name=toolkit_name,
779
+ server_url=connection_config.url,
780
+ server_headers=connection_config.headers,
781
+ description=f"Inspect available tools, prompts, and resources from MCP toolkit '{toolkit_name}'"
782
+ )
783
+ except Exception as e:
784
+ logger.error(f"Failed to create MCP inspection tool for toolkit '{toolkit_name}': {e}")
785
+ return None
786
+
787
+ def get_tools(self) -> List[BaseTool]:
788
+ """Get the list of tools provided by this toolkit."""
789
+ logger.info(f"MCP toolkit '{self.toolkit_name}' returning {len(self.tools)} tools")
790
+ if len(self.tools) > 0:
791
+ tool_names = [t.name if hasattr(t, 'name') else str(t) for t in self.tools]
792
+ logger.info(f"MCP toolkit '{self.toolkit_name}' tools: {tool_names}")
793
+ return self.tools
794
+
795
+ async def refresh_tools(self):
796
+ """Manually refresh tools from the MCP toolkit."""
797
+ if not self.toolkit_name:
798
+ logger.warning("Cannot refresh tools: toolkit_name not set")
799
+ return
800
+
801
+ try:
802
+ from ..clients.mcp_manager import get_mcp_manager
803
+ manager = get_mcp_manager()
804
+ await manager.refresh_server(self.toolkit_name)
805
+ logger.info(f"Successfully refreshed tools for toolkit {self.toolkit_name}")
806
+ except Exception as e:
807
+ logger.error(f"Failed to refresh tools for toolkit {self.toolkit_name}: {e}")
808
+
809
+ async def get_server_health(self) -> Dict[str, Any]:
810
+ """Get health status of the configured MCP toolkit."""
811
+ if not self.toolkit_name:
812
+ return {"status": "not_configured"}
813
+
814
+ try:
815
+ from ..clients.mcp_manager import get_mcp_manager
816
+ manager = get_mcp_manager()
817
+ health_info = await manager.get_server_health(self.toolkit_name)
818
+ return health_info
819
+ except Exception as e:
820
+ logger.error(f"Failed to get server health for {self.toolkit_name}: {e}")
821
+ return {"status": "error", "error": str(e)}
822
+
823
+
824
+ def get_tools(tool_config: dict, alita_client, llm=None, memory_store=None) -> List[BaseTool]:
825
+ """
826
+ Create MCP tools from configuration.
827
+ This function is called by the main tool loading system.
828
+
829
+ Args:
830
+ tool_config: Tool configuration dictionary
831
+ alita_client: Alita client instance
832
+ llm: Language model (not used by MCP tools)
833
+ memory_store: Memory store (not used by MCP tools)
834
+
835
+ Returns:
836
+ List of configured MCP tools
837
+ """
838
+ settings = tool_config.get('settings', {})
839
+ toolkit_name = tool_config.get('toolkit_name')
840
+
841
+ # Extract required fields
842
+ url = settings.get('url')
843
+ headers = settings.get('headers')
844
+
845
+ if not toolkit_name:
846
+ logger.error("MCP toolkit configuration missing required 'toolkit_name'")
847
+ return []
848
+
849
+ if not url:
850
+ logger.error("MCP toolkit configuration missing required 'url'")
851
+ return []
852
+
853
+ # Type conversion for numeric settings that may come as strings from config
854
+ return McpToolkit.get_toolkit(
855
+ url=url,
856
+ headers=headers,
857
+ timeout=safe_int(settings.get('timeout'), 60),
858
+ discovery_mode=settings.get('discovery_mode', 'dynamic'),
859
+ discovery_interval=safe_int(settings.get('discovery_interval'), 300),
860
+ selected_tools=settings.get('selected_tools', []),
861
+ enable_caching=settings.get('enable_caching', True),
862
+ cache_ttl=safe_int(settings.get('cache_ttl'), 300),
863
+ toolkit_name=toolkit_name,
864
+ client=alita_client
865
+ ).get_tools()
866
+
867
+
868
+ # Utility functions for managing MCP discovery
869
+ async def start_global_discovery():
870
+ """Start the global MCP discovery service."""
871
+ from ..clients.mcp_discovery import init_discovery_service
872
+ await init_discovery_service()
873
+
874
+
875
+ async def stop_global_discovery():
876
+ """Stop the global MCP discovery service."""
877
+ from ..clients.mcp_discovery import shutdown_discovery_service
878
+ await shutdown_discovery_service()
879
+
880
+
881
+ async def register_mcp_server_for_discovery(toolkit_name: str, connection_config):
882
+ """Register an MCP server for global discovery."""
883
+ from ..clients.mcp_discovery import get_discovery_service
884
+ service = get_discovery_service()
885
+ await service.register_server(toolkit_name, connection_config)
886
+
887
+
888
+ def get_all_discovered_servers():
889
+ """Get status of all discovered servers."""
890
+ from ..clients.mcp_discovery import get_discovery_service
891
+ service = get_discovery_service()
892
+ return service.get_server_health()