Skip to content

A programming framework for agentic AI

Update AGS (Support Workbenches ++) (#6736)

Victor Dibiab2cef7f47c32
diff --git a/python/packages/autogen-studio/README.md b/python/packages/autogen-studio/README.md
index 75393d467..8f7452de7 100644
--- a/python/packages/autogen-studio/README.md
+++ b/python/packages/autogen-studio/README.md
@@ -124,6 +124,45 @@ AutoGen Studio also takes several parameters to customize the application:
Now that you have AutoGen Studio installed and running, you are ready to explore its capabilities, including defining and modifying agent workflows, interacting with agents and sessions, and expanding agent skills.
+## AutoGen Studio Lite
+
+AutoGen Studio Lite provides a lightweight way to quickly prototype and experiment with AI agent teams. It's designed for rapid experimentation without the full database setup.
+
+### CLI Usage
+
+Launch Studio Lite from the command line:
+
+```bash
+# Quick start with default team
+autogenstudio lite
+
+# Use custom team file
+autogenstudio lite --team ./my_team.json --port 8080
+
+# Custom session name
+autogenstudio lite --session-name "My Experiment" --auto-open
+```
+
+### Programmatic Usage
+
+Use Studio Lite directly in your Python code:
+
+```python
+from autogenstudio.lite import LiteStudio
+
+# Quick start with default team
+studio = LiteStudio()
+# Use with AutoGen team objects
+from autogen_agentchat.teams import RoundRobinGroupChat
+team = RoundRobinGroupChat([agent1, agent2], termination_condition=...)
+
+# Context manager usage
+with LiteStudio(team=team) as studio:
+ # Studio runs in background
+ # Do other work here
+ pass
+```
+
#### Local frontend development server
See `./frontend/README.md`
diff --git a/python/packages/autogen-studio/autogenstudio/cli.py b/python/packages/autogen-studio/autogenstudio/cli.py
index 8bf27915c..373f13e08 100644
--- a/python/packages/autogen-studio/autogenstudio/cli.py
+++ b/python/packages/autogen-studio/autogenstudio/cli.py
@@ -131,6 +131,35 @@ def version():
typer.echo(f"AutoGen Studio CLI version: {VERSION}")
+def lite(
+ team: Optional[str] = None,
+ host: str = "127.0.0.1",
+ port: int = 8080,
+ auto_open: bool = True,
+ session_name: str = "Lite Session",
+):
+ """
+ Launch AutoGen Studio in lightweight mode for quick experimentation.
+
+ Args:
+ team (str, optional): Path to team JSON/YAML file. If not provided, uses a default team.
+ host (str): Host to run on. Defaults to 127.0.0.1.
+ port (int): Port to run on. Defaults to 8080.
+ auto_open (bool): Auto-open browser. Defaults to True.
+ session_name (str): Name for the auto-created session.
+ """
+ from autogenstudio.lite import LiteStudio
+
+ # Create and start studio instance
+ studio = LiteStudio(team=team, host=host, port=port, auto_open=auto_open, session_name=session_name)
+
+ try:
+ studio.start() # Blocking call for CLI
+ except KeyboardInterrupt:
+ studio.stop()
+
+
def run():
app()
diff --git a/python/packages/autogen-studio/autogenstudio/database/db_manager.py b/python/packages/autogen-studio/autogenstudio/database/db_manager.py
index 226e1dcd5..f3eceebbe 100644
--- a/python/packages/autogen-studio/autogenstudio/database/db_manager.py
+++ b/python/packages/autogen-studio/autogenstudio/database/db_manager.py
@@ -87,11 +87,14 @@ class DatabaseManager:
return Response(message="Failed to initialize migrations", status=False)
# Handle existing database
- if auto_upgrade or self._should_auto_upgrade():
+ if auto_upgrade:
logger.info("Checking database schema...")
if self.schema_manager.ensure_schema_up_to_date():
return Response(message="Database schema is up to date", status=True)
return Response(message="Database upgrade failed", status=False)
+ elif self._should_auto_upgrade():
+ logger.info("Schema changes detected, but auto_upgrade is disabled. Skipping migration check.")
+ logger.info("To enable automatic migrations, set auto_upgrade=True")
return Response(message="Database is ready", status=True)
diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/db.py b/python/packages/autogen-studio/autogenstudio/datamodel/db.py
index 6aed5a620..ea8f427ed 100644
--- a/python/packages/autogen-studio/autogenstudio/datamodel/db.py
+++ b/python/packages/autogen-studio/autogenstudio/datamodel/db.py
@@ -93,9 +93,7 @@ class Run(BaseDBModel, table=True):
__table_args__ = {"sqlite_autoincrement": True}
- session_id: Optional[int] = Field(
- default=None, sa_column=Column(Integer, ForeignKey("session.id", ondelete="CASCADE"), nullable=False)
- )
+ session_id: int = Field(sa_column=Column(Integer, ForeignKey("session.id", ondelete="CASCADE"), nullable=False))
status: RunStatus = Field(default=RunStatus.CREATED)
# Store the original user task
@@ -107,11 +105,9 @@ class Run(BaseDBModel, table=True):
team_result: Union[TeamResult, dict] = Field(default=None, sa_column=Column(JSON))
error_message: Optional[str] = None
- version: Optional[str] = "0.0.1"
messages: Union[List[Message], List[dict]] = Field(default_factory=list, sa_column=Column(JSON))
model_config = ConfigDict(json_encoders={datetime: lambda v: v.isoformat()}) # type: ignore[call-arg]
- user_id: Optional[str] = None
class Gallery(BaseDBModel, table=True):
@@ -122,7 +118,7 @@ class Gallery(BaseDBModel, table=True):
id="",
name="",
metadata=GalleryMetadata(author="", version=""),
- components=GalleryComponents(agents=[], models=[], tools=[], terminations=[], teams=[]),
+ components=GalleryComponents(agents=[], models=[], tools=[], terminations=[], teams=[], workbenches=[]),
),
sa_column=Column(JSON),
)
diff --git a/python/packages/autogen-studio/autogenstudio/datamodel/types.py b/python/packages/autogen-studio/autogenstudio/datamodel/types.py
index e36ad0e8e..cab12555c 100644
--- a/python/packages/autogen-studio/autogenstudio/datamodel/types.py
+++ b/python/packages/autogen-studio/autogenstudio/datamodel/types.py
@@ -7,7 +7,7 @@ from autogen_agentchat.messages import ChatMessage, TextMessage
from autogen_core import ComponentModel
from autogen_core.models import UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient
-from pydantic import BaseModel, ConfigDict, SecretStr
+from pydantic import BaseModel, ConfigDict, Field, SecretStr
class MessageConfig(BaseModel):
@@ -70,6 +70,7 @@ class GalleryComponents(BaseModel):
tools: List[ComponentModel]
terminations: List[ComponentModel]
teams: List[ComponentModel]
+ workbenches: List[ComponentModel]
class GalleryConfig(BaseModel):
@@ -96,6 +97,9 @@ class UISettings(BaseModel):
show_llm_call_events: bool = False
expanded_messages_by_default: bool = True
show_agent_flow_by_default: bool = True
+ human_input_timeout_minutes: int = Field(
+ default=3, ge=1, le=30, description="Human input timeout in minutes (1-30)"
+ )
class SettingsConfig(BaseModel):
diff --git a/python/packages/autogen-studio/autogenstudio/gallery/builder.py b/python/packages/autogen-studio/autogenstudio/gallery/builder.py
index 6d5067b20..55a124367 100644
--- a/python/packages/autogen-studio/autogenstudio/gallery/builder.py
+++ b/python/packages/autogen-studio/autogenstudio/gallery/builder.py
@@ -1,19 +1,29 @@
import os
-from datetime import datetime
+import tempfile
from typing import List, Optional
-import anthropic
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
-from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
-from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat
+from autogen_agentchat.conditions import (
+ HandoffTermination,
+ MaxMessageTermination,
+ SourceMatchTermination,
+ StopMessageTermination,
+ TextMentionTermination,
+ TextMessageTermination,
+ TimeoutTermination,
+ TokenUsageTermination,
+)
+from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat, Swarm
from autogen_core import ComponentModel
from autogen_core.models import ModelInfo
+from autogen_core.tools import StaticWorkbench
from autogen_ext.agents.web_surfer import MultimodalWebSurfer
from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor
from autogen_ext.models.anthropic import AnthropicChatCompletionClient
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.models.openai._openai_client import AzureOpenAIChatCompletionClient
from autogen_ext.tools.code_execution import PythonCodeExecutionTool
+from autogen_ext.tools.mcp import McpWorkbench, StdioServerParams, StreamableHttpServerParams
from autogenstudio.datamodel import GalleryComponents, GalleryConfig, GalleryMetadata
@@ -32,6 +42,7 @@ class GalleryBuilder:
self.models: List[ComponentModel] = []
self.tools: List[ComponentModel] = []
self.terminations: List[ComponentModel] = []
+ self.workbenches: List[ComponentModel] = []
# Default metadata
self.metadata = GalleryMetadata(
@@ -112,6 +123,13 @@ class GalleryBuilder:
self.terminations.append(self._update_component_metadata(termination, label, description))
return self
+ def add_workbench(
+ self, workbench: ComponentModel, label: Optional[str] = None, description: Optional[str] = None
+ ) -> "GalleryBuilder":
+ """Add a workbench component to the gallery with optional custom label and description."""
+ self.workbenches.append(self._update_component_metadata(workbench, label, description))
+ return self
+
def build(self) -> GalleryConfig:
"""Build and return the complete gallery."""
# Update timestamps
@@ -128,6 +146,7 @@ class GalleryBuilder:
models=self.models,
tools=self.tools,
terminations=self.terminations,
+ workbenches=self.workbenches,
),
)
@@ -220,6 +239,64 @@ def create_default_gallery() -> GalleryConfig:
description="Termination condition that ends the conversation when either a message contains 'TERMINATE' or the maximum number of messages is reached.",
)
+ # Add examples of new termination conditions
+
+ # StopMessageTermination - terminates when a StopMessage is received
+ stop_msg_term = StopMessageTermination()
+ builder.add_termination(
+ stop_msg_term.dump_component(),
+ label="Stop Message Termination",
+ description="Terminates the conversation when a StopMessage is received from any agent.",
+ )
+
+ # TokenUsageTermination - terminates based on token usage limits
+ token_usage_term = TokenUsageTermination(max_total_token=1000, max_prompt_token=800, max_completion_token=200)
+ builder.add_termination(
+ token_usage_term.dump_component(),
+ label="Token Usage Termination",
+ description="Terminates the conversation when token usage limits are reached (1000 total, 800 prompt, 200 completion).",
+ )
+
+ # TimeoutTermination - terminates after a specified duration
+ timeout_term = TimeoutTermination(timeout_seconds=300) # 5 minutes
+ builder.add_termination(
+ timeout_term.dump_component(),
+ label="Timeout Termination",
+ description="Terminates the conversation after 5 minutes (300 seconds) have elapsed.",
+ )
+
+ # HandoffTermination - terminates when handoff to specific target occurs
+ handoff_term = HandoffTermination(target="user_proxy")
+ builder.add_termination(
+ handoff_term.dump_component(),
+ label="Handoff Termination",
+ description="Terminates the conversation when a handoff to 'user_proxy' is detected.",
+ )
+
+ # SourceMatchTermination - terminates when specific sources respond
+ source_match_term = SourceMatchTermination(sources=["assistant_agent", "critic_agent"])
+ builder.add_termination(
+ source_match_term.dump_component(),
+ label="Source Match Termination",
+ description="Terminates the conversation when either 'assistant_agent' or 'critic_agent' responds.",
+ )
+
+ # TextMessageTermination - terminates on TextMessage from specific source
+ text_msg_term = TextMessageTermination(source="assistant_agent")
+ builder.add_termination(
+ text_msg_term.dump_component(),
+ label="Text Message Termination",
+ description="Terminates the conversation when a TextMessage is received from 'assistant_agent'.",
+ )
+
+ # Create a complex termination combining multiple conditions
+ complex_term = (token_usage_term | timeout_term) & (calc_text_term | stop_msg_term)
+ builder.add_termination(
+ complex_term.dump_component(),
+ label="Complex Termination",
+ description="Complex termination: (token usage OR timeout) AND (text mention 'TERMINATE' OR stop message).",
+ )
+
# Create calculator team
calc_team = RoundRobinGroupChat(participants=[calc_assistant], termination_condition=calc_or_term)
builder.add_team(
@@ -243,6 +320,31 @@ def create_default_gallery() -> GalleryConfig:
description="A team with 2 agents - an AssistantAgent (with a calculator tool) and a CriticAgent in a SelectorGroupChat team.",
)
+ # Create Swarm team - agents with handoff capabilities
+ # Alice agent with handoff to Bob
+ alice_agent = AssistantAgent(
+ name="Alice",
+ system_message="You are Alice, a helpful assistant. You specialize in general questions. If someone asks about technical topics or needs detailed analysis, hand off to Bob by saying 'Let me hand this over to Bob for a detailed analysis.'",
+ model_client=base_model,
+ handoffs=["Bob"],
+ )
+
+ # Bob agent with handoff back to Alice
+ bob_agent = AssistantAgent(
+ name="Bob",
+ system_message="You are Bob, a technical specialist. You handle detailed technical analysis. If the conversation becomes general or the user needs basic assistance, hand off to Alice by saying 'Let me hand this back to Alice for general assistance.'",
+ model_client=base_model,
+ handoffs=["Alice"],
+ )
+
+ # Create simple Swarm team with handoff-based conversation
+ swarm_team = Swarm(participants=[alice_agent, bob_agent], termination_condition=calc_or_term)
+ builder.add_team(
+ swarm_team.dump_component(),
+ label="Swarm Team",
+ description="A team with 2 agents (Alice and Bob) that use handoff messages to transfer conversation control between agents based on expertise.",
+ )
+
# Create web surfer agent
websurfer_agent = MultimodalWebSurfer(
name="websurfer_agent",
@@ -413,9 +515,116 @@ Read the above conversation. Then select the next role from {participants} to pl
description="A team with 3 agents - a Research Assistant that performs web searches and analyzes information, a Verifier that ensures research quality and completeness, and a Summary Agent that provides a detailed markdown summary of the research as a report to the user.",
)
+ # Add workbenches to the gallery
+
+ # Create a static workbench with basic tools
+ static_workbench = StaticWorkbench(tools=[tools.calculator_tool, tools.fetch_webpage_tool])
+ builder.add_workbench(
+ static_workbench.dump_component(),
+ label="Basic Tools Workbench",
+ description="A static workbench containing basic tools like calculator and webpage fetcher for common tasks.",
+ )
+
+ # Create an MCP workbench for fetching web content using mcp-server-fetch
+ # Note: This requires uv to be installed (comes with uv package manager)
+ fetch_server_params = StdioServerParams(
+ command="uv",
+ args=["tool", "run", "mcp-server-fetch"],
+ read_timeout_seconds=60,
+ )
+ mcp_workbench = McpWorkbench(server_params=fetch_server_params)
+ builder.add_workbench(
+ mcp_workbench.dump_component(),
+ label="MCP Fetch Workbench",
+ description="An MCP workbench that provides web content fetching capabilities using the mcp-server-fetch MCP server. Allows agents to fetch and read content from web pages and APIs.",
+ )
+
+ # Create an MCP workbench with StreamableHttpServerParams for HTTP-based MCP servers
+ # Note: This is an example - adjust URL and authentication as needed
+ streamable_server_params = StreamableHttpServerParams(
+ url="http://localhost:8005/mcp",
+ headers={"Authorization": "Bearer your-api-key", "Content-Type": "application/json"},
+ timeout=30,
+ sse_read_timeout=60 * 5,
+ terminate_on_close=True,
+ )
+ streamable_mcp_workbench = McpWorkbench(server_params=streamable_server_params)
+ builder.add_workbench(
+ streamable_mcp_workbench.dump_component(),
+ label="MCP Streamable HTTP Workbench",
+ description="An MCP workbench that connects to HTTP-based MCP servers using Server-Sent Events (SSE). Suitable for cloud-hosted MCP services and custom HTTP MCP implementations.",
+ )
+
+ # Create an MCP workbench for filesystem operations
+ # Note: This requires npx to be installed and allows access to specified directories
+
+ # Use cross-platform paths for filesystem access
+ user_home = os.path.expanduser("~")
+ temp_dir = tempfile.gettempdir() # Cross-platform temp directory
+
+ filesystem_server_params = StdioServerParams(
+ command="npx",
+ args=["-y", "@modelcontextprotocol/server-filesystem", user_home, temp_dir],
+ read_timeout_seconds=60,
+ )
+ filesystem_mcp_workbench = McpWorkbench(server_params=filesystem_server_params)
+ builder.add_workbench(
+ filesystem_mcp_workbench.dump_component(),
+ label="MCP Filesystem Workbench",
+ description="An MCP workbench that provides filesystem access capabilities using the @modelcontextprotocol/server-filesystem MCP server. Allows agents to read, write, and manage files and directories within specified allowed paths.",
+ )
+
+ # Create an MCP workbench for testing with everything server
+ # Note: This requires npx to be installed and provides comprehensive MCP testing tools
+ everything_server_params = StdioServerParams(
+ command="npx",
+ args=["-y", "@modelcontextprotocol/server-everything"],
+ read_timeout_seconds=60,
+ )
+ everything_mcp_workbench = McpWorkbench(server_params=everything_server_params)
+ builder.add_workbench(
+ everything_mcp_workbench.dump_component(),
+ label="MCP Test Server",
+ description="An MCP workbench that provides comprehensive testing tools using the @modelcontextprotocol/server-everything MCP server. Includes various tools for testing MCP functionality, protocol features, and capabilities.",
+ )
+
return builder.build()
+def create_default_lite_team():
+ """Create a simple default team for lite mode - a basic assistant with calculator tool."""
+ import json
+ import os
+ import tempfile
+
+ # model clients require API keys to be set in the environment or passed in
+ # as arguments. For testing purposes, we set them to "test" if not already set.
+ for key in ["OPENAI_API_KEY", "AZURE_OPENAI_API_KEY", "ANTHROPIC_API_KEY"]:
+ if not os.environ.get(key):
+ os.environ[key] = "test"
+
+ # Create base model client
+ base_model = OpenAIChatCompletionClient(model="gpt-4o-mini")
+
+ # Create assistant agent with calculator tool
+ assistant = AssistantAgent(
+ name="assistant",
+ model_client=base_model,
+ tools=[tools.calculator_tool],
+ )
+
+ # Create termination condition
+ termination = TextMentionTermination(text="TERMINATE") | MaxMessageTermination(max_messages=5)
+
+ # Create simple round robin team
+ team = RoundRobinGroupChat(participants=[assistant], termination_condition=termination)
+
+ # Create temporary file with team data
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
+ json.dump(team.dump_component().model_dump(), f, indent=2)
+ return f.name
+
+
if __name__ == "__main__":
# Create and save the gallery
gallery = create_default_gallery()
diff --git a/python/packages/autogen-studio/autogenstudio/lite/__init__.py b/python/packages/autogen-studio/autogenstudio/lite/__init__.py
new file mode 100644
index 000000000..9f7c560b5
--- /dev/null
+++ b/python/packages/autogen-studio/autogenstudio/lite/__init__.py
@@ -0,0 +1,3 @@
+from .studio import LiteStudio
+
+__all__ = ["LiteStudio"]
diff --git a/python/packages/autogen-studio/autogenstudio/lite/studio.py b/python/packages/autogen-studio/autogenstudio/lite/studio.py
new file mode 100644
index 000000000..94b25cd85
--- /dev/null
+++ b/python/packages/autogen-studio/autogenstudio/lite/studio.py
@@ -0,0 +1,245 @@
+import json
+import os
+import subprocess
+import tempfile
+import threading
+import time
+import webbrowser
+from pathlib import Path
+from typing import Any, Dict, Union
+
+import uvicorn
+from autogen_core import ComponentModel
+
+
+class LiteStudio:
+ """
+ Core class for managing AutoGen Studio lite mode instances.
+ Supports both file-based and programmatic team configurations.
+ """
+
+ def __init__(
+ self,
+ team: Union[str, Path, Dict[str, Any], ComponentModel, None] = None,
+ host: str = "127.0.0.1",
+ port: int = 8080,
+ session_name: str = "Lite Session",
+ auto_open: bool = True,
+ ):
+ """
+ Initialize LiteStudio instance.
+
+ Args:
+ team: Team configuration - can be:
+ - str: Path to team JSON file
+ - Path: Path object to team JSON file
+ - Dict[str, Any]: Team configuration dictionary
+ - ComponentModel: AutoGen ComponentModel instance
+ - None: Creates default team
+ host: Host to run server on
+ port: Port to run server on
+ session_name: Name for the auto-created session
+ auto_open: Whether to auto-open browser
+ """
+ self.host = host
+ self.port = port
+ self.session_name = session_name
+ self.auto_open = auto_open
+ self.server_process = None
+ self.server_thread = None # Handle team loading
+ self.team_file_path = self._load_team(team)
+
+ def _load_team(self, team: Union[str, Path, Dict[str, Any], ComponentModel, None]) -> str:
+ """
+ Load team from file path, object, or create default.
+ Returns the file path to the team JSON.
+ Args:
+ team: Can be file path (str/Path), dict, ComponentModel, or None
+ """
+ if team is None:
+ # Create default team
+ from autogenstudio.gallery.builder import create_default_lite_team
+
+ return create_default_lite_team()
+
+ elif isinstance(team, (str, Path)):
+ # File path provided
+ team_path = Path(team)
+ if not team_path.exists():
+ raise FileNotFoundError(f"Team file not found: {team_path}")
+ return str(team_path.absolute())
+
+ elif isinstance(team, dict):
+ # Team dict provided - save to temp file
+ temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False)
+ try:
+ json.dump(team, temp_file, indent=2)
+ temp_file.flush()
+ return temp_file.name
+ finally:
+ temp_file.close()
+
+ elif isinstance(team, ComponentModel):
+ # ComponentModel - use model_dump directly
+ team_dict = team.model_dump()
+ temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False)
+ try:
+ json.dump(team_dict, temp_file, indent=2)
+ temp_file.flush()
+ return temp_file.name
+ finally:
+ temp_file.close()
+
+ else:
+ # Try to serialize other team objects
+ team_dict = None
+
+ # Try dump_component() method (AutoGen teams)
+ if hasattr(team, "dump_component"):
+ component = team.dump_component()
+ if hasattr(component, "model_dump"):
+ team_dict = component.model_dump()
+ elif hasattr(component, "dict"):
+ team_dict = component.dict()
+ else:
+ team_dict = dict(component)
+
+ # Try model_dump() method (Pydantic v2)
+ elif hasattr(team, "model_dump"):
+ team_dict = team.model_dump()
+
+ # Try dict() method (Pydantic v1)
+ elif hasattr(team, "dict"):
+ team_dict = team.dict()
+
+ if team_dict is None:
+ raise ValueError(
+ f"Cannot serialize team object of type {type(team)}. "
+ f"Expected: file path, dict, ComponentModel, or object with dump_component()/model_dump()/dict() method."
+ )
+
+ # Save serialized team to temp file
+ temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False)
+ try:
+ json.dump(team_dict, temp_file, indent=2)
+ temp_file.flush()
+ return temp_file.name
+ finally:
+ temp_file.close()
+
+ def _get_env_file_path(self) -> str:
+ """Get path for environment variables file."""
+ app_dir = os.path.join(os.path.expanduser("~"), ".autogenstudio")
+ if not os.path.exists(app_dir):
+ os.makedirs(app_dir, exist_ok=True)
+ return os.path.join(app_dir, "temp_env_vars.env")
+
+ def _setup_environment(self) -> str:
+ """
+ Setup environment variables for lite mode.
+ Returns path to the environment file.
+ """
+ env_vars = {
+ "AUTOGENSTUDIO_HOST": self.host,
+ "AUTOGENSTUDIO_PORT": str(self.port),
+ "AUTOGENSTUDIO_LITE_MODE": "true",
+ "AUTOGENSTUDIO_API_DOCS": "false",
+ "AUTOGENSTUDIO_AUTH_DISABLED": "true",
+ "AUTOGENSTUDIO_LITE_SESSION_NAME": self.session_name,
+ "AUTOGENSTUDIO_LITE_TEAM_FILE": self.team_file_path,
+ "AUTOGENSTUDIO_DATABASE_URI": "sqlite:///:memory:",
+ }
+
+ env_file_path = self._get_env_file_path()
+ with open(env_file_path, "w") as temp_env:
+ for key, value in env_vars.items():
+ temp_env.write(f"{key}={value}\n")
+
+ return env_file_path
+
+ def _setup_browser_opening(self):
+ """Setup browser opening in a separate thread."""
+ if self.auto_open:
+
+ def open_browser():
+ time.sleep(3) # Wait for server startup
+ url = f"http://{self.host}:{self.port}/lite"
+ webbrowser.open(url)
+
+ threading.Thread(target=open_browser, daemon=True).start()
+
+ def start(self, background: bool = False):
+ """
+ Start the lite studio server.
+ Args:
+ background: If True, run server in background thread
+ """
+ # Check if already running
+ if self.server_thread and self.server_thread.is_alive():
+ raise RuntimeError("LiteStudio is already running")
+
+ # Setup environment
+ env_file_path = self._setup_environment()
+
+ # Setup browser opening
+ self._setup_browser_opening()
+
+ if background:
+ # Run server in background thread
+ def run_server():
+ uvicorn.run(
+ "autogenstudio.web.app:app",
+ host=self.host,
+ port=self.port,
+ workers=1,
+ env_file=env_file_path,
+ )
+
+ self.server_thread = threading.Thread(target=run_server, daemon=True)
+ self.server_thread.start()
+ else:
+ # Run server in foreground (blocking)
+ uvicorn.run(
+ "autogenstudio.web.app:app",
+ host=self.host,
+ port=self.port,
+ workers=1,
+ env_file=env_file_path,
+ )
+
+ def stop(self):
+ """Stop the lite studio server."""
+ if self.server_thread and self.server_thread.is_alive():
+ # For background threads, we can't easily stop uvicorn
+ # This is a limitation - in production you'd want proper shutdown
+ self.server_thread.join(timeout=5)
+ self.server_thread = None
+
+ def __enter__(self):
+ """Context manager entry - start in background."""
+ self.start(background=True)
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb): # type: ignore
+ """Context manager exit - stop server."""
+ self.stop()
+
+ @classmethod
+ def shutdown_port(cls, port: int):
+ """
+ Utility to shutdown any process running on the specified port.
+ Args:
+ port: Port number to shutdown
+ """
+ try:
+ # Try to find and kill process on port (Unix/Linux/Mac)
+ result = subprocess.run(["lsof", "-ti", f":{port}"], capture_output=True, text=True)
+
+ if result.returncode == 0 and result.stdout.strip():
+ pids = result.stdout.strip().split("\n")
+ for pid in pids:
+ subprocess.run(["kill", "-9", pid], check=False)
+
+ except (subprocess.SubprocessError, FileNotFoundError):
+ # lsof might not be available on all systems
+ pass
diff --git a/python/packages/autogen-studio/autogenstudio/mcp/callbacks.py b/python/packages/autogen-studio/autogenstudio/mcp/callbacks.py
new file mode 100644
index 000000000..417f0f846
--- /dev/null
+++ b/python/packages/autogen-studio/autogenstudio/mcp/callbacks.py
@@ -0,0 +1,186 @@
+import asyncio
+import uuid
+from datetime import datetime, timezone
+from typing import Any, Dict, Tuple
+
+from loguru import logger
+from mcp.shared.context import RequestContext
+from mcp.shared.session import RequestResponder
+from mcp.types import (
+ ClientResult,
+ CreateMessageRequestParams,
+ CreateMessageResult,
+ ElicitRequestParams,
+ ElicitResult,
+ ErrorData,
+ ServerNotification,
+ ServerRequest,
+ TextContent,
+)
+
+from .utils import extract_real_error, serialize_for_json
+from .wsbridge import MCPWebSocketBridge
+
+
+def create_message_handler(bridge: MCPWebSocketBridge):
+ """Create a message handler callback that streams MCP protocol messages to the UI"""
+
+ async def message_handler(
+ message: RequestResponder[ServerRequest, ClientResult] | ServerNotification | Exception,
+ ) -> None:
+ try:
+ if isinstance(message, Exception):
+ await bridge.on_mcp_activity(
+ "error", f"Protocol error: {str(message)}", {"details": extract_real_error(message)}
+ )
+
+ elif hasattr(message, "method"):
+ method = getattr(message, "method", "unknown")
+ params = getattr(message, "params", None)
+
+ await bridge.on_mcp_activity(
+ "protocol",
+ f"MCP {method}",
+ {
+ "method": method,
+ "params": serialize_for_json(params) if params else None,
+ "message_type": type(message).__name__,
+ },
+ )
+
+ else:
+ await bridge.on_mcp_activity(
+ "protocol",
+ f"{type(message).__name__}",
+ {
+ "message_type": type(message).__name__,
+ "content": serialize_for_json(message) if hasattr(message, "model_dump") else str(message),
+ },
+ )
+
+ except Exception as e:
+ logger.error(f"Error in message handler: {extract_real_error(e)}")
+
+ return message_handler
+
+
+def create_sampling_callback(bridge: MCPWebSocketBridge):
+ """Create a sampling callback that handles AI sampling requests from tools"""
+
+ async def sampling_callback(
+ context: RequestContext[Any, Any, Any],
+ params: CreateMessageRequestParams,
+ ) -> CreateMessageResult | ErrorData:
+ try:
+ request_id = str(uuid.uuid4())
+
+ await bridge.on_mcp_activity(
+ "sampling",
+ f"Tool requested AI sampling for {len(params.messages)} message(s)",
+ {
+ "request_id": request_id,
+ "params": serialize_for_json(params.model_dump()),
+ "context": "Tool is requesting AI to generate a response",
+ },
+ )
+
+ dummy_response = CreateMessageResult(
+ role="assistant",
+ content=TextContent(
+ type="text",
+ text="[AutoGen Studio Default Sampling Response - This is a placeholder response for AI sampling requests. In a production setup, this would be handled by your configured LLM.]",
+ ),
+ model="autogen-studio-default",
+ )
+
+ await bridge.on_mcp_activity(
+ "sampling",
+ "Provided default sampling response to tool",
+ {
+ "request_id": request_id,
+ "response": serialize_for_json(dummy_response.model_dump()),
+ "note": "This is a placeholder response - configure an LLM for real sampling",
+ },
+ )
+
+ logger.info("Handled sampling request with default response")
+ return dummy_response
+
+ except Exception as e:
+ error_msg = extract_real_error(e)
+ logger.error(f"Error in sampling callback: {error_msg}")
+
+ await bridge.on_mcp_activity("error", f"Sampling callback error: {error_msg}", {"error": error_msg})
+
+ return ErrorData(code=-32603, message=f"Sampling failed: {error_msg}")
+
+ return sampling_callback
+
+
+def create_elicitation_callback(
+ bridge: MCPWebSocketBridge,
+) -> Tuple[Any, Dict[str, asyncio.Future[ElicitResult | ErrorData]]]:
+ """Create an elicitation callback that handles user input requests from tools"""
+
+ async def elicitation_callback(
+ context: RequestContext[Any, Any, Any],
+ params: ElicitRequestParams,
+ ) -> ElicitResult | ErrorData:
+ try:
+ request_id = str(uuid.uuid4())
+
+ await bridge.on_mcp_activity(
+ "elicitation",
+ f"Tool requesting user input: {params.message}",
+ {
+ "request_id": request_id,
+ "message": params.message,
+ "requestedSchema": serialize_for_json(params.requestedSchema) if params.requestedSchema else None,
+ "context": "Tool is requesting additional information from user",
+ },
+ )
+
+ await bridge.on_elicitation_request(
+ request_id,
+ params.message,
+ serialize_for_json(params.requestedSchema) if params.requestedSchema else None,
+ )
+
+ response_future: asyncio.Future[ElicitResult | ErrorData] = asyncio.Future()
+ bridge.pending_elicitations[request_id] = response_future
+
+ try:
+ user_response = await asyncio.wait_for(response_future, timeout=60.0)
+
+ await bridge.on_mcp_activity(
+ "elicitation",
+ "User responded to elicitation request",
+ {"request_id": request_id, "response": serialize_for_json(user_response), "status": "completed"},
+ )
+
+ return user_response
+
+ except asyncio.TimeoutError:
+ logger.warning(f"User did not respond to elicitation request {request_id} within 60 seconds")
+ error_msg = "User did not respond to elicitation request within 60 seconds"
+
+ await bridge.on_mcp_activity(
+ "error",
+ f"Elicitation timeout: {error_msg}",
+ {"request_id": request_id, "error": error_msg, "timeout": 60},
+ )
+
+ return ErrorData(code=-32603, message=error_msg)
+
+ finally:
+ bridge.pending_elicitations.pop(request_id, None)
+
+ except Exception as e:
+ error_msg = extract_real_error(e)
+ logger.error(f"Error in elicitation callback: {error_msg}")
+
+ await bridge.on_mcp_activity("error", f"Elicitation callback error: {error_msg}", {"error": error_msg})
+
+ return ErrorData(code=-32603, message=f"Elicitation failed: {error_msg}")
+
+ return elicitation_callback, bridge.pending_elicitations
diff --git a/python/packages/autogen-studio/autogenstudio/mcp/client.py b/python/packages/autogen-studio/autogenstudio/mcp/client.py
new file mode 100644
index 000000000..a8a076ee7
--- /dev/null
+++ b/python/packages/autogen-studio/autogenstudio/mcp/client.py
@@ -0,0 +1,121 @@
+from typing import Any, Dict, Protocol
+
+from mcp import ClientSession
+
+from .utils import McpOperationError, extract_real_error, serialize_for_json
+
+
+class MCPEventHandler(Protocol):
+ """Interface for handling MCP events"""
+
+ async def on_initialized(self, session_id: str, capabilities: Any) -> None:
+ """Called when MCP session is initialized"""
+ ...
+
+ async def on_operation_result(self, operation: str, data: Dict[str, Any]) -> None:
+ """Called when an MCP operation completes successfully"""
+ ...
+
+ async def on_operation_error(self, operation: str, error: str) -> None:
+ """Called when an MCP operation fails"""
+ ...
+
+ async def on_mcp_activity(self, activity_type: str, message: str, details: Dict[str, Any]) -> None:
+ """Called for MCP protocol activity"""
+ ...
+
+ async def on_elicitation_request(self, request_id: str, message: str, requested_schema: Any) -> None:
+ """Called when MCP requests user input"""
+ ...
+
+
+class MCPClient:
+ """Handles MCP protocol operations independently of transport"""
+
+ def __init__(self, session: ClientSession, session_id: str, event_handler: MCPEventHandler):
+ self.session = session
+ self.session_id = session_id
+ self.event_handler = event_handler
+ self._initialized = False
+ self._capabilities = None
+
+ async def initialize(self) -> None:
+ """Initialize the MCP session"""
+ try:
+ initialize_result = await self.session.initialize()
+
+ if initialize_result:
+ self._capabilities = initialize_result.capabilities
+ else:
+ self._capabilities = None
+
+ self._initialized = True
+
+ # Notify handler
+ await self.event_handler.on_initialized(
+ self.session_id, serialize_for_json(self._capabilities.model_dump()) if self._capabilities else None
+ )
+
+ except Exception as e:
+ await self.event_handler.on_operation_error("initialize", str(e))
+ raise
+
+ async def handle_operation(self, operation: Dict[str, Any]) -> None:
+ """Handle an MCP operation - this preserves the exact behavior of handle_mcp_operation"""
+ operation_type = operation.get("operation")
+
+ try:
+ if operation_type == "list_tools":
+ result = await self.session.list_tools()
+ tools_data = [serialize_for_json(tool.model_dump()) for tool in result.tools]
+ await self.event_handler.on_operation_result("list_tools", {"tools": tools_data})
+
+ elif operation_type == "call_tool":
+ tool_name = operation.get("tool_name")
+ arguments = operation.get("arguments", {})
+ if not tool_name:
+ raise McpOperationError("Tool name is required")
+
+ result = await self.session.call_tool(tool_name, arguments)
+ await self.event_handler.on_operation_result(
+ "call_tool", {"tool_name": tool_name, "result": serialize_for_json(result.model_dump())}
+ )
+
+ elif operation_type == "list_resources":
+ result = await self.session.list_resources()
+ await self.event_handler.on_operation_result("list_resources", serialize_for_json(result.model_dump()))
+
+ elif operation_type == "read_resource":
+ uri = operation.get("uri")
+ if not uri:
+ raise McpOperationError("Resource URI is required")
+
+ result = await self.session.read_resource(uri)
+ await self.event_handler.on_operation_result("read_resource", serialize_for_json(result.model_dump()))
+
+ elif operation_type == "list_prompts":
+ result = await self.session.list_prompts()
+ prompts_data = [serialize_for_json(prompt.model_dump()) for prompt in result.prompts]
+ await self.event_handler.on_operation_result("list_prompts", {"prompts": prompts_data})
+
+ elif operation_type == "get_prompt":
+ name = operation.get("name")
+ arguments = operation.get("arguments")
+ if not name:
+ raise McpOperationError("Prompt name is required")
+
+ result = await self.session.get_prompt(name, arguments)
+ await self.event_handler.on_operation_result("get_prompt", serialize_for_json(result.model_dump()))
+
+ else:
+ await self.event_handler.on_operation_error(
+ operation_type or "unknown", f"Unknown operation: {operation_type}"
+ )
+
+ except Exception as e:
+ real_error = extract_real_error(e)
+ await self.event_handler.on_operation_error(operation_type or "unknown", real_error)
+
+ @property
+ def capabilities(self):
+ return self._capabilities
diff --git a/python/packages/autogen-studio/autogenstudio/mcp/utils.py b/python/packages/autogen-studio/autogenstudio/mcp/utils.py
new file mode 100644
index 000000000..457957a5b
--- /dev/null
+++ b/python/packages/autogen-studio/autogenstudio/mcp/utils.py
@@ -0,0 +1,88 @@
+from typing import Any, List
+
+from fastapi import WebSocketDisconnect
+from pydantic.networks import AnyUrl
+
+
+class McpOperationError(Exception):
+ """Raised when MCP operation fails"""
+
+ pass
+
+
+def extract_real_error(e: Exception) -> str:
+ """Extract the real error message from potentially wrapped exceptions"""
+ error_parts: List[str] = []
+
+ # Handle ExceptionGroup (Python 3.11+)
+ if hasattr(e, "exceptions") and getattr(e, "exceptions", None):
+ exceptions_list = getattr(e, "exceptions", [])
+ for sub_exc in exceptions_list:
+ error_parts.append(f"{type(sub_exc).__name__}: {str(sub_exc)}")
+
+ # Handle chained exceptions
+ elif hasattr(e, "__cause__") and e.__cause__:
+ current = e
+ while current:
+ error_parts.append(f"{type(current).__name__}: {str(current)}")
+ current = getattr(current, "__cause__", None)
+
+ # Handle context exceptions
+ elif hasattr(e, "__context__") and e.__context__:
+ error_parts.append(f"Context: {type(e.__context__).__name__}: {str(e.__context__)}")
+ error_parts.append(f"Error: {type(e).__name__}: {str(e)}")
+
+ # Default case
+ else:
+ error_parts.append(f"{type(e).__name__}: {str(e)}")
+
+ return " | ".join(error_parts)
+
+
+def serialize_for_json(obj: Any) -> Any:
+ """Convert objects to JSON-serializable format"""
+ if isinstance(obj, AnyUrl):
+ return str(obj)
+ elif isinstance(obj, dict):
+ return {str(k): serialize_for_json(v) for k, v in obj.items()}
+ elif isinstance(obj, list):
+ return [serialize_for_json(item) for item in obj]
+ elif hasattr(obj, "model_dump"):
+ return serialize_for_json(obj.model_dump())
+ else:
+ return obj
+
+
+def is_websocket_disconnect(e: Exception) -> bool:
+ """Check if an exception (potentially nested) is a WebSocket disconnect"""
+
+ def check_exception(exc: BaseException) -> bool:
+ if isinstance(exc, WebSocketDisconnect):
+ return True
+
+ exc_name = type(exc).__name__
+ exc_str = str(exc)
+
+ if "WebSocketDisconnect" in exc_name or "NO_STATUS_RCVD" in exc_str:
+ return True
+
+ # Recursively check ExceptionGroup
+ if hasattr(exc, "exceptions") and getattr(exc, "exceptions", None):
+ exceptions_list = getattr(exc, "exceptions", [])
+ for sub_exc in exceptions_list:
+ if check_exception(sub_exc):
+ return True
+
+ # Check chained exceptions
+ if hasattr(exc, "__cause__") and exc.__cause__:
+ if check_exception(exc.__cause__):
+ return True
+
+ # Check context exceptions
+ if hasattr(exc, "__context__") and exc.__context__:
+ if check_exception(exc.__context__):
+ return True
+
+ return False
+
+ return check_exception(e)
diff --git a/python/packages/autogen-studio/autogenstudio/mcp/wsbridge.py b/python/packages/autogen-studio/autogenstudio/mcp/wsbridge.py
new file mode 100644
index 000000000..d723b0853
--- /dev/null
+++ b/python/packages/autogen-studio/autogenstudio/mcp/wsbridge.py
@@ -0,0 +1,215 @@
+import asyncio
+import json
+from datetime import datetime, timezone
+from typing import Any, Dict, Optional
+
+from fastapi import WebSocket
+from loguru import logger
+from mcp import ClientSession
+from mcp.types import ElicitResult, ErrorData
+
+from .client import MCPClient, MCPEventHandler
+from .utils import extract_real_error, is_websocket_disconnect, serialize_for_json
+
+
+class MCPWebSocketBridge(MCPEventHandler):
+ """Bridges WebSocket connections to MCP operations"""
+
+ def __init__(self, websocket: WebSocket, session_id: str):
+ self.websocket = websocket
+ self.session_id = session_id
+ self.mcp_client: Optional[MCPClient] = None
+ self.pending_elicitations: Dict[str, asyncio.Future[ElicitResult | ErrorData]] = {}
+ self._running = True
+
+ async def send_message(self, message: Dict[str, Any]) -> None:
+ """Send a message through the WebSocket"""
+ try:
+ from fastapi.websockets import WebSocketState
+
+ if self.websocket.client_state == WebSocketState.CONNECTED:
+ serialized_message = serialize_for_json(message)
+ await self.websocket.send_json(serialized_message)
+ except Exception as e:
+ real_error = extract_real_error(e)
+ logger.error(f"Error sending WebSocket message: {real_error}")
+
+ # Implement MCPEventHandler interface
+ async def on_initialized(self, session_id: str, capabilities: Any) -> None:
+ await self.send_message(
+ {
+ "type": "initialized",
+ "session_id": session_id,
+ "capabilities": capabilities,
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+
+ async def on_operation_result(self, operation: str, data: Dict[str, Any]) -> None:
+ await self.send_message(
+ {
+ "type": "operation_result",
+ "operation": operation,
+ "data": data,
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+
+ async def on_operation_error(self, operation: str, error: str) -> None:
+ await self.send_message(
+ {
+ "type": "operation_error",
+ "operation": operation,
+ "error": error,
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+
+ async def on_mcp_activity(self, activity_type: str, message: str, details: Dict[str, Any]) -> None:
+ await self.send_message(
+ {
+ "type": "mcp_activity",
+ "activity_type": activity_type,
+ "message": message,
+ "details": details,
+ "session_id": self.session_id,
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+
+ async def on_elicitation_request(self, request_id: str, message: str, requested_schema: Any) -> None:
+ await self.send_message(
+ {
+ "type": "elicitation_request",
+ "request_id": request_id,
+ "message": message,
+ "requestedSchema": requested_schema,
+ "session_id": self.session_id,
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+
+ def set_mcp_client(self, mcp_client: MCPClient) -> None:
+ """Set the MCP client after initialization"""
+ self.mcp_client = mcp_client
+
+ async def handle_websocket_message(self, message: Dict[str, Any]) -> None:
+ """Handle incoming WebSocket messages"""
+ message_type = message.get("type")
+
+ # Update last activity for session tracking
+ from datetime import datetime, timezone
+
+ from ..web.routes.mcp import active_sessions
+
+ if self.session_id in active_sessions:
+ active_sessions[self.session_id]["last_activity"] = datetime.now(timezone.utc)
+
+ if message_type == "operation":
+ # CRITICAL: Run in background task to avoid blocking message loop
+ # This preserves the exact behavior from the original code
+ if self.mcp_client:
+ asyncio.create_task(self.mcp_client.handle_operation(message))
+ else:
+ await self.send_message(
+ {
+ "type": "error",
+ "error": "MCP client not initialized",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+
+ elif message_type == "ping":
+ await self.send_message({"type": "pong", "timestamp": datetime.now(timezone.utc).isoformat()})
+
+ elif message_type == "elicitation_response":
+ await self._handle_elicitation_response(message)
+
+ else:
+ await self.send_message(
+ {
+ "type": "error",
+ "error": f"Unknown message type: {message_type}",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+
+ async def _handle_elicitation_response(self, message: Dict[str, Any]) -> None:
+ """Handle user response to elicitation request"""
+ request_id = message.get("request_id")
+
+ if not request_id:
+ await self.send_message(
+ {
+ "type": "error",
+ "error": "Missing request_id in elicitation response",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+ return
+
+ if request_id in self.pending_elicitations:
+ try:
+ action = message.get("action", "cancel")
+ data = message.get("data", {})
+
+ if action == "accept":
+ result = ElicitResult(action="accept", content=data)
+ elif action == "decline":
+ result = ElicitResult(action="decline")
+ else:
+ result = ElicitResult(action="cancel")
+
+ future = self.pending_elicitations[request_id]
+ if not future.done():
+ future.set_result(result)
+ else:
+ logger.warning(f"Future for elicitation request {request_id} was already done")
+
+ except Exception as e:
+ error_msg = extract_real_error(e)
+ logger.error(f"Error processing elicitation response: {error_msg}")
+
+ future = self.pending_elicitations.get(request_id)
+ if future and not future.done():
+ future.set_result(
+ ErrorData(code=-32603, message=f"Error processing elicitation response: {error_msg}")
+ )
+ else:
+ logger.warning(f"Unknown elicitation request_id: {request_id}")
+ await self.send_message(
+ {
+ "type": "operation_error",
+ "error": f"Unknown elicitation request_id: {request_id}",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+
+ async def run(self) -> None:
+ """Main message loop"""
+ try:
+ while self._running:
+ try:
+ raw_message = await self.websocket.receive_text()
+ message = json.loads(raw_message)
+ await self.handle_websocket_message(message)
+
+ except json.JSONDecodeError:
+ logger.warning(f"Invalid JSON received from session {self.session_id}")
+ await self.send_message(
+ {
+ "type": "error",
+ "error": "Invalid message format",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+
+ except Exception as e:
+ if not is_websocket_disconnect(e):
+ real_error = extract_real_error(e)
+ logger.error(f"Error in message loop: {real_error}")
+ raise
+
+ def stop(self) -> None:
+ """Stop the bridge"""
+ self._running = False
diff --git a/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py b/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py
index eb35ac79e..f143a5d4d 100644
--- a/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py
+++ b/python/packages/autogen-studio/autogenstudio/teammanager/teammanager.py
@@ -4,7 +4,7 @@ import logging
import os
import time
from pathlib import Path
-from typing import AsyncGenerator, Callable, List, Optional, Sequence, Union
+from typing import Any, AsyncGenerator, Awaitable, Callable, Dict, List, Optional, Sequence, Union
import aiofiles
import yaml
@@ -20,13 +20,17 @@ from ..web.managers.run_context import RunContext
logger = logging.getLogger(__name__)
+SyncInputFunc = Callable[[str], str]
+AsyncInputFunc = Callable[[str, Optional[CancellationToken]], Awaitable[str]]
+InputFuncType = Union[SyncInputFunc, AsyncInputFunc]
+
class RunEventLogger(logging.Handler):
"""Event logger that queues LLMCallEvents for streaming"""
def __init__(self):
super().__init__()
- self.events = asyncio.Queue()
+ self.events: asyncio.Queue[LLMCallEventMessage] = asyncio.Queue()
def emit(self, record: logging.LogRecord):
if isinstance(record.msg, LLMCallEvent):
@@ -41,7 +45,7 @@ class TeamManager:
self._run_context = RunContext()
@staticmethod
- async def load_from_file(path: Union[str, Path]) -> dict:
+ async def load_from_file(path: Union[str, Path]) -> Any:
"""Load team configuration from JSON/YAML file"""
path = Path(path)
if not path.exists():
@@ -56,10 +60,10 @@ class TeamManager:
raise ValueError(f"Unsupported file format: {path.suffix}")
@staticmethod
- async def load_from_directory(directory: Union[str, Path]) -> List[dict]:
+ async def load_from_directory(directory: Union[str, Path]) -> List[Any]:
"""Load all team configurations from a directory"""
directory = Path(directory)
- configs = []
+ configs: List[Any] = []
valid_extensions = {".json", ".yaml", ".yml"}
for path in directory.iterdir():
@@ -74,8 +78,8 @@ class TeamManager:
async def _create_team(
self,
- team_config: Union[str, Path, dict, ComponentModel],
- input_func: Optional[Callable] = None,
+ team_config: Union[str, Path, Dict[str, Any], ComponentModel],
+ input_func: Optional[InputFuncType] = None,
env_vars: Optional[List[EnvironmentVariable]] = None,
) -> BaseGroupChat:
"""Create team instance from config"""
@@ -83,8 +87,10 @@ class TeamManager:
config = await self.load_from_file(team_config)
elif isinstance(team_config, dict):
config = team_config
- else:
+ elif isinstance(team_config, ComponentModel):
config = team_config.model_dump()
+ else:
+ raise ValueError(f"Unsupported team_config type: {type(team_config)}")
# Load env vars into environment if provided
if env_vars:
@@ -94,7 +100,7 @@ class TeamManager:
self._team = BaseGroupChat.load_component(config)
- for agent in self._team._participants:
+ for agent in self._team._participants: # type: ignore
if hasattr(agent, "input_func") and isinstance(agent, UserProxyAgent) and input_func:
agent.input_func = input_func
@@ -103,8 +109,8 @@ class TeamManager:
async def run_stream(
self,
task: str | BaseChatMessage | Sequence[BaseChatMessage] | None,
- team_config: Union[str, Path, dict, ComponentModel],
- input_func: Optional[Callable] = None,
+ team_config: Union[str, Path, Dict[str, Any], ComponentModel],
+ input_func: Optional[InputFuncType] = None,
cancellation_token: Optional[CancellationToken] = None,
env_vars: Optional[List[EnvironmentVariable]] = None,
) -> AsyncGenerator[Union[BaseAgentEvent | BaseChatMessage | LLMCallEvent, BaseChatMessage, TeamResult], None]:
@@ -141,15 +147,15 @@ class TeamManager:
# Ensure cleanup happens
if team and hasattr(team, "_participants"):
- for agent in team._participants:
+ for agent in team._participants: # type: ignore
if hasattr(agent, "close"):
await agent.close()
async def run(
self,
task: str | BaseChatMessage | Sequence[BaseChatMessage] | None,
- team_config: Union[str, Path, dict, ComponentModel],
- input_func: Optional[Callable] = None,
+ team_config: Union[str, Path, Dict[str, Any], ComponentModel],
+ input_func: Optional[InputFuncType] = None,
cancellation_token: Optional[CancellationToken] = None,
env_vars: Optional[List[EnvironmentVariable]] = None,
) -> TeamResult:
@@ -165,6 +171,6 @@ class TeamManager:
finally:
if team and hasattr(team, "_participants"):
- for agent in team._participants:
+ for agent in team._participants: # type: ignore
if hasattr(agent, "close"):
await agent.close()
diff --git a/python/packages/autogen-studio/autogenstudio/validation/validation_service.py b/python/packages/autogen-studio/autogenstudio/validation/validation_service.py
index b4a8c60cb..b9d95a19c 100644
--- a/python/packages/autogen-studio/autogenstudio/validation/validation_service.py
+++ b/python/packages/autogen-studio/autogenstudio/validation/validation_service.py
@@ -1,7 +1,6 @@
# validation/validation_service.py
import importlib
-from calendar import c
-from typing import Any, Dict, List, Optional
+from typing import List, Optional
from autogen_core import ComponentModel, is_component_class
from pydantic import BaseModel
@@ -70,7 +69,7 @@ class ValidationService:
@staticmethod
def validate_config_schema(component: ComponentModel) -> List[ValidationError]:
"""Validate the component configuration against its schema"""
- errors = []
+ errors: List[ValidationError] = []
try:
# Convert to ComponentModel for initial validation
model = component.model_copy(deep=True)
@@ -123,17 +122,57 @@ class ValidationService:
component_class.load_component(model)
return None
except Exception as e:
- return ValidationError(
- field="instantiation",
- error=f"Failed to instantiate component: {str(e)}",
- suggestion="Check that the component can be properly instantiated with the given config",
- )
+ error_str = str(e)
+
+ # Check for version compatibility issues
+ if "component_version" in error_str and "_from_config_past_version is not implemented" in error_str:
+ # Extract component information for a better error message
+ try:
+ # Get the current component version
+ module_path, class_name = component.provider.rsplit(".", maxsplit=1)
+ module = importlib.import_module(module_path)
+ component_class = getattr(module, class_name)
+ current_version = getattr(component_class, "component_version", None)
+ config_version = component.component_version or component.version or 1
+
+ return ValidationError(
+ field="component_version",
+ error=f"Component version mismatch: Your configuration uses version {config_version}, but the component requires version {current_version}",
+ suggestion=f"Update your component configuration to use version {current_version}. Set 'component_version: {current_version}' in your configuration.",
+ )
+ except Exception:
+ # Fallback to a more general version error message
+ return ValidationError(
+ field="component_version",
+ error="Component version compatibility issue detected",
+ suggestion="Your component configuration version is outdated. Update the 'component_version' field to match the latest component requirements.",
+ )
+
+ # Check for other common instantiation issues
+ elif "Could not import provider" in error_str or "ImportError" in error_str:
+ return ValidationError(
+ field="provider",
+ error=f"Provider import failed: {error_str}",
+ suggestion="Ensure the provider module is installed and the import path is correct",
+ )
+ elif "component_config_schema" in error_str:
+ return ValidationError(
+ field="config",
+ error="Component configuration schema validation failed",
+ suggestion="Check that your configuration matches the component's expected schema",
+ )
+ else:
+ return ValidationError(
+ field="instantiation",
+ error=f"Failed to instantiate component: {error_str}",
+ suggestion="Check that the component can be properly instantiated with the given config",
+ )
@classmethod
def validate(cls, component: ComponentModel) -> ValidationResponse:
"""Validate a component configuration"""
- errors = []
- warnings = []
+ errors: List[ValidationError] = []
+ warnings: List[ValidationError] = []
# Check provider
if provider_error := cls.validate_provider(component.provider):
diff --git a/python/packages/autogen-studio/autogenstudio/version.py b/python/packages/autogen-studio/autogenstudio/version.py
index 0dc9be3b2..57a95b183 100644
--- a/python/packages/autogen-studio/autogenstudio/version.py
+++ b/python/packages/autogen-studio/autogenstudio/version.py
@@ -1,3 +1,3 @@
-VERSION = "0.4.2.2"
+VERSION = "0.4.3"
__version__ = VERSION
APP_NAME = "autogenstudio"
diff --git a/python/packages/autogen-studio/autogenstudio/web/app.py b/python/packages/autogen-studio/autogenstudio/web/app.py
index d69191c2d..d4022555f 100644
--- a/python/packages/autogen-studio/autogenstudio/web/app.py
+++ b/python/packages/autogen-studio/autogenstudio/web/app.py
@@ -15,7 +15,7 @@ from .auth.middleware import AuthMiddleware
from .config import settings
from .deps import cleanup_managers, init_auth_manager, init_managers, register_auth_dependencies
from .initialization import AppInitializer
-from .routes import gallery, runs, sessions, settingsroute, teams, validation, ws
+from .routes import gallery, mcp, runs, sessions, settingsroute, teams, validation, ws
# Initialize application
app_file_path = os.path.dirname(os.path.abspath(__file__))
@@ -141,6 +141,20 @@ api.include_router(
responses={404: {"description": "Not found"}},
)
+# api.include_router(
+# maker.router,
+# prefix="/maker",
+# tags=["maker"],
+# responses={404: {"description": "Not found"}},
+# )
+
+api.include_router(
+ mcp.router,
+ prefix="/mcp",
+ tags=["mcp"],
+ responses={404: {"description": "Not found"}},
+)
+
# Version endpoint
diff --git a/python/packages/autogen-studio/autogenstudio/web/auth/manager.py b/python/packages/autogen-studio/autogenstudio/web/auth/manager.py
index 846f8f124..ab16e0432 100644
--- a/python/packages/autogen-studio/autogenstudio/web/auth/manager.py
+++ b/python/packages/autogen-studio/autogenstudio/web/auth/manager.py
@@ -1,6 +1,6 @@
import os
-from datetime import datetime, timedelta
-from typing import Any, Dict, Optional
+from datetime import datetime, timedelta, timezone
+from typing import Any, Dict
import jwt
import yaml
@@ -47,7 +47,7 @@ class AuthManager:
logger.warning("JWT secret not configured, using insecure token")
return "dummy_token_" + user.id
- expiry = datetime.utcnow() + timedelta(minutes=self.config.token_expiry_minutes)
+ expiry = datetime.now(timezone.utc) + timedelta(minutes=self.config.token_expiry_minutes)
payload = {
"sub": user.id,
"name": user.name,
@@ -94,12 +94,12 @@ class AuthManager:
roles=payload.get("roles", ["user"]),
)
- except jwt.ExpiredSignatureError:
+ except jwt.ExpiredSignatureError as e:
logger.warning(f"Expired token received: {token[:10]}...")
- raise InvalidTokenException() from InvalidTokenException()
- except jwt.InvalidTokenError:
+ raise InvalidTokenException() from e
+ except jwt.InvalidTokenError as e:
logger.warning(f"Invalid token received: {token[:10]}...")
- raise InvalidTokenException() from InvalidTokenException()
+ raise InvalidTokenException() from e
def is_valid_token(self, token: str) -> bool:
"""Check if a JWT token is valid."""
@@ -123,14 +123,14 @@ class AuthManager:
return cls(config)
except Exception as e:
logger.error(f"Failed to load auth config from {yaml_path}: {str(e)}")
- raise ConfigurationException(f"Failed to load auth config: {str(e)}") from ConfigurationException()
+ raise ConfigurationException(f"Failed to load auth config: {str(e)}") from e
@classmethod
def from_env(cls) -> Self:
"""Create AuthManager from environment variables."""
auth_type = os.environ.get("AUTOGENSTUDIO_AUTH_TYPE", "none")
- config_dict = {
+ config_dict: Dict[str, Any] = {
"type": auth_type,
"jwt_secret": os.environ.get("AUTOGENSTUDIO_JWT_SECRET"),
"token_expiry_minutes": int(os.environ.get("AUTOGENSTUDIO_TOKEN_EXPIRY", "60")),
diff --git a/python/packages/autogen-studio/autogenstudio/web/auth/middleware.py b/python/packages/autogen-studio/autogenstudio/web/auth/middleware.py
index b6aef611c..7c2809c8b 100644
--- a/python/packages/autogen-studio/autogenstudio/web/auth/middleware.py
+++ b/python/packages/autogen-studio/autogenstudio/web/auth/middleware.py
@@ -3,8 +3,9 @@ import re
from fastapi import Request, Response, WebSocket
from loguru import logger
-from starlette.middleware.base import BaseHTTPMiddleware
+from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.status import HTTP_401_UNAUTHORIZED
+from starlette.types import ASGIApp
from .exceptions import AuthException
from .manager import AuthManager
@@ -15,11 +16,11 @@ class AuthMiddleware(BaseHTTPMiddleware):
Middleware for handling authentication for all routes.
"""
- def __init__(self, app, auth_manager: AuthManager):
+ def __init__(self, app: ASGIApp, auth_manager: AuthManager) -> None:
super().__init__(app)
self.auth_manager = auth_manager
- async def dispatch(self, request: Request, call_next):
+ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
"""Process each request, authenticating as needed."""
# Skip auth for OPTIONS requests (CORS preflight)
if request.method == "OPTIONS":
@@ -45,7 +46,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
return await call_next(request)
# WebSocket handling (special case)
- if request.url.path.startswith("/api/ws"):
+ if request.url.path.startswith("/api/ws") or request.url.path.startswith("/api/maker"):
# For WebSockets, we'll add auth in the WebSocket accept handler
# Just pass through here
return await call_next(request)
@@ -81,7 +82,7 @@ class WebSocketAuthMiddleware:
Not a middleware in the traditional sense - used in WebSocket endpoint.
"""
- def __init__(self, auth_manager: AuthManager):
+ def __init__(self, auth_manager: AuthManager) -> None:
self.auth_manager = auth_manager
async def authenticate(self, websocket: WebSocket) -> bool:
diff --git a/python/packages/autogen-studio/autogenstudio/web/config.py b/python/packages/autogen-studio/autogenstudio/web/config.py
index 2a5c47ddf..30d54bb57 100644
--- a/python/packages/autogen-studio/autogenstudio/web/config.py
+++ b/python/packages/autogen-studio/autogenstudio/web/config.py
@@ -4,7 +4,7 @@ from pydantic_settings import BaseSettings
class Settings(BaseSettings):
- DATABASE_URI: str = "sqlite:///./autogen04202.db"
+ DATABASE_URI: str = "sqlite:///./autogen04203.db"
API_DOCS: bool = False
CLEANUP_INTERVAL: int = 300 # 5 minutes
SESSION_TIMEOUT: int = 3600 # 1 hour
@@ -12,6 +12,11 @@ class Settings(BaseSettings):
DEFAULT_USER_ID: str = "[email protected]"
UPGRADE_DATABASE: bool = False
+ # Lite mode settings
+ LITE_MODE: bool = False
+ LITE_TEAM_FILE: str = ""
+ LITE_SESSION_NAME: str = ""
+
model_config = {"env_prefix": "AUTOGENSTUDIO_"}
diff --git a/python/packages/autogen-studio/autogenstudio/web/deps.py b/python/packages/autogen-studio/autogenstudio/web/deps.py
index 7d560cbb1..0a4e16ff9 100644
--- a/python/packages/autogen-studio/autogenstudio/web/deps.py
+++ b/python/packages/autogen-studio/autogenstudio/web/deps.py
@@ -1,4 +1,5 @@
# api/deps.py
+import json
import logging
import os
from contextlib import contextmanager
@@ -16,12 +17,19 @@ from .managers.connection import WebSocketManager
logger = logging.getLogger(__name__)
+# Helper functions for environment detection
+
+
+def is_lite_mode() -> bool:
+ """Check if lite mode is enabled via environment variable"""
+ return os.getenv("AUTOGENSTUDIO_LITE_MODE", "").lower() in ["true", "1"]
+
+
# Global manager instances
_db_manager: Optional[DatabaseManager] = None
_websocket_manager: Optional[WebSocketManager] = None
_team_manager: Optional[TeamManager] = None
_auth_manager: Optional[AuthManager] = None
-# Context manager for database sessions
@contextmanager
@@ -83,6 +91,13 @@ async def get_current_user(request: Request) -> str:
def init_auth_manager(config_dir: Path) -> AuthManager:
"""Initialize authentication manager"""
+ # Check if auth is explicitly disabled via environment variable
+ if os.getenv("AUTOGENSTUDIO_AUTH_DISABLED", "").lower() in ["true", "1"]:
+ config = AuthConfig(type="none")
+ auth_manager = AuthManager(config)
+ logger.info("Authentication disabled via environment variable")
+ return auth_manager
+
auth_config_path = os.environ.get("AUTOGENSTUDIO_AUTH_CONFIG")
if auth_config_path and os.path.exists(auth_config_path):
@@ -125,10 +140,24 @@ async def init_managers(database_uri: str, config_dir: str | Path, app_root: str
try:
# Initialize database manager
_db_manager = DatabaseManager(engine_uri=database_uri, base_dir=app_root)
- _db_manager.initialize_database(auto_upgrade=settings.UPGRADE_DATABASE)
- # init default team config
- await _db_manager.import_teams_from_directory(config_dir, settings.DEFAULT_USER_ID, check_exists=True)
+ # Initialize database - use simplified approach for lite mode
+ if is_lite_mode():
+ logger.info("Initializing database for lite mode...")
+ # Use the database manager's initialization but skip migrations
+ # since lite mode uses in-memory database that doesn't need persistence
+ _db_manager.initialize_database(auto_upgrade=False, force_init_alembic=False)
+ else:
+ # Full initialization with migrations for regular mode
+ _db_manager.initialize_database(auto_upgrade=settings.UPGRADE_DATABASE)
+
+ # Skip default team import for lite mode (we'll load our specific team)
+ if not is_lite_mode():
+ # init default team config
+ await _db_manager.import_teams_from_directory(config_dir, settings.DEFAULT_USER_ID, check_exists=True)
+
+ # Initialize lite mode if enabled
+ await init_lite_mode(_db_manager)
# Initialize connection manager
_websocket_manager = WebSocketManager(db_manager=_db_manager)
@@ -227,3 +256,45 @@ def require_managers(*manager_names: str):
return True
return Depends(dependency)
+
+
+async def init_lite_mode(db_manager: DatabaseManager) -> None:
+ """Initialize lite mode specific setup: load team and create default session"""
+ if not is_lite_mode():
+ return
+
+ logger.info("Initializing lite mode...")
+
+ # Load team from file (required in lite mode)
+ if settings.LITE_TEAM_FILE and os.path.exists(settings.LITE_TEAM_FILE):
+ try:
+ # Import the team into the database
+ result = await db_manager.import_team(settings.LITE_TEAM_FILE, settings.DEFAULT_USER_ID, check_exists=True)
+ if result.status and result.data:
+ team_id = result.data.get("id")
+ logger.info(f"Loaded team from file {settings.LITE_TEAM_FILE} with ID: {team_id}")
+
+ # Create a default session with this team
+ from ..datamodel.db import Session
+
+ session_name = settings.LITE_SESSION_NAME or "Lite Mode Session"
+
+ session = Session(user_id=settings.DEFAULT_USER_ID, team_id=team_id, name=session_name)
+
+ session_result = db_manager.upsert(session)
+ if session_result.status and session_result.data:
+ session_id = session_result.data.get("id")
+ logger.info(f"Created lite mode session: {session_name} (ID: {session_id})")
+ else:
+ logger.error(f"Failed to create session: {session_result.message}")
+ raise Exception(f"Failed to create session: {session_result.message}")
+ else:
+ logger.error(f"Failed to import team from file: {result.message}")
+ raise Exception(f"Failed to import team: {result.message}")
+
+ except Exception as e:
+ logger.error(f"Failed to load team from file {settings.LITE_TEAM_FILE}: {str(e)}")
+ raise
+ else:
+ logger.error("No team file specified for lite mode")
+ raise Exception("Lite mode requires a team file to be specified")
diff --git a/python/packages/autogen-studio/autogenstudio/web/managers/connection.py b/python/packages/autogen-studio/autogenstudio/web/managers/connection.py
index 0c6d1f73d..96d524d6e 100644
--- a/python/packages/autogen-studio/autogenstudio/web/managers/connection.py
+++ b/python/packages/autogen-studio/autogenstudio/web/managers/connection.py
@@ -1,8 +1,8 @@
import asyncio
import logging
-import trace
import traceback
from datetime import date, datetime, time, timezone
+from pathlib import Path
from typing import Any, Callable, Dict, Optional, Sequence, Union
from autogen_agentchat.base import TaskResult
@@ -18,7 +18,7 @@ from autogen_agentchat.messages import (
ToolCallExecutionEvent,
ToolCallRequestEvent,
)
-from autogen_core import CancellationToken
+from autogen_core import CancellationToken, ComponentModel
from autogen_core import Image as AGImage
from fastapi import WebSocket, WebSocketDisconnect
@@ -83,7 +83,10 @@ class WebSocketManager:
return False
async def start_stream(
- self, run_id: int, task: str | ChatMessage | Sequence[ChatMessage] | None, team_config: Dict
+ self,
+ run_id: int,
+ task: str | ChatMessage | Sequence[ChatMessage] | None,
+ team_config: str | Path | Dict[str, Any] | ComponentModel,
) -> None:
"""Start streaming task execution with proper run management"""
if run_id not in self._connections or run_id in self._closed_connections:
diff --git a/python/packages/autogen-studio/autogenstudio/web/routes/mcp.py b/python/packages/autogen-studio/autogenstudio/web/routes/mcp.py
new file mode 100644
index 000000000..5ff9da7a5
--- /dev/null
+++ b/python/packages/autogen-studio/autogenstudio/web/routes/mcp.py
@@ -0,0 +1,240 @@
+import base64
+import json
+import uuid
+from datetime import datetime, timezone
+from typing import Any, Dict
+
+from autogen_ext.tools.mcp._config import (
+ McpServerParams,
+ SseServerParams,
+ StdioServerParams,
+ StreamableHttpServerParams,
+)
+from fastapi import APIRouter, WebSocket, WebSocketDisconnect
+from loguru import logger
+from mcp import ClientSession, StdioServerParameters
+from mcp.client.sse import sse_client
+from mcp.client.stdio import stdio_client
+from mcp.client.streamable_http import streamablehttp_client
+from pydantic import BaseModel
+
+from ...mcp.callbacks import (
+ create_elicitation_callback,
+ create_message_handler,
+ create_sampling_callback,
+)
+from ...mcp.client import MCPClient
+from ...mcp.utils import extract_real_error, is_websocket_disconnect, serialize_for_json
+from ...mcp.wsbridge import MCPWebSocketBridge
+
+router = APIRouter()
+
+# Global session tracking for status endpoint
+active_sessions: Dict[str, Dict[str, Any]] = {}
+
+
+class CreateWebSocketConnectionRequest(BaseModel):
+ server_params: McpServerParams
+
+
+async def create_mcp_session(bridge: MCPWebSocketBridge, server_params: McpServerParams, session_id: str):
+ """Create MCP session based on server parameters"""
+
+ # Create callbacks using the bridge
+ message_handler = create_message_handler(bridge)
+ sampling_callback = create_sampling_callback(bridge)
+ elicitation_callback, _ = create_elicitation_callback(bridge)
+
+ if isinstance(server_params, StdioServerParams):
+ stdio_params = StdioServerParameters(
+ command=server_params.command, args=server_params.args, env=server_params.env
+ )
+ async with stdio_client(stdio_params) as (read, write):
+ async with ClientSession(
+ read,
+ write,
+ message_handler=message_handler,
+ sampling_callback=sampling_callback,
+ elicitation_callback=elicitation_callback,
+ ) as session:
+ mcp_client = MCPClient(session, session_id, bridge)
+ bridge.set_mcp_client(mcp_client)
+
+ # Initialize and run
+ await mcp_client.initialize()
+
+ # Store session info
+ active_sessions[session_id] = {
+ "created_at": datetime.now(timezone.utc),
+ "last_activity": datetime.now(timezone.utc),
+ "capabilities": serialize_for_json(mcp_client.capabilities.model_dump())
+ if mcp_client.capabilities
+ else None,
+ }
+
+ # Run the bridge message loop
+ await bridge.run()
+
+ elif isinstance(server_params, SseServerParams):
+ async with sse_client(server_params.url) as (read, write):
+ async with ClientSession(
+ read,
+ write,
+ message_handler=message_handler,
+ sampling_callback=sampling_callback,
+ elicitation_callback=elicitation_callback,
+ ) as session:
+ mcp_client = MCPClient(session, session_id, bridge)
+ bridge.set_mcp_client(mcp_client)
+
+ await mcp_client.initialize()
+
+ active_sessions[session_id] = {
+ "created_at": datetime.now(timezone.utc),
+ "last_activity": datetime.now(timezone.utc),
+ "capabilities": serialize_for_json(mcp_client.capabilities.model_dump())
+ if mcp_client.capabilities
+ else None,
+ }
+
+ await bridge.run()
+
+ elif isinstance(server_params, StreamableHttpServerParams):
+ async with streamablehttp_client(server_params.url) as (read, write, _):
+ async with ClientSession(
+ read,
+ write,
+ message_handler=message_handler,
+ sampling_callback=sampling_callback,
+ elicitation_callback=elicitation_callback,
+ ) as session:
+ mcp_client = MCPClient(session, session_id, bridge)
+ bridge.set_mcp_client(mcp_client)
+
+ await mcp_client.initialize()
+
+ active_sessions[session_id] = {
+ "created_at": datetime.now(timezone.utc),
+ "last_activity": datetime.now(timezone.utc),
+ "capabilities": serialize_for_json(mcp_client.capabilities.model_dump())
+ if mcp_client.capabilities
+ else None,
+ }
+
+ await bridge.run()
+
+ else:
+ raise ValueError(f"Unsupported server params type: {type(server_params)}")
+
+
[email protected]("/ws/{session_id}")
+async def mcp_websocket(websocket: WebSocket, session_id: str):
+ """Main WebSocket endpoint - now a thin layer"""
+ await websocket.accept()
+ logger.info(f"MCP WebSocket connection established for session {session_id}")
+
+ bridge = None
+
+ try:
+ # Parse server parameters
+ query_params = dict(websocket.query_params)
+ server_params_encoded = query_params.get("server_params")
+
+ if not server_params_encoded:
+ await websocket.close(code=4000, reason="Missing server_params")
+ return
+
+ decoded_params = base64.b64decode(server_params_encoded).decode("utf-8")
+ server_params_dict = json.loads(decoded_params)
+
+ # Create appropriate server params object
+ if server_params_dict.get("type") == "StdioServerParams":
+ server_params = StdioServerParams(**server_params_dict)
+ elif server_params_dict.get("type") == "SseServerParams":
+ server_params = SseServerParams(**server_params_dict)
+ elif server_params_dict.get("type") == "StreamableHttpServerParams":
+ server_params = StreamableHttpServerParams(**server_params_dict)
+ else:
+ await websocket.close(code=4000, reason="Invalid server parameters")
+ return
+
+ # Create bridge and run MCP session
+ bridge = MCPWebSocketBridge(websocket, session_id)
+ await create_mcp_session(bridge, server_params, session_id)
+
+ except WebSocketDisconnect:
+ logger.info(f"MCP WebSocket session {session_id} disconnected normally")
+ except Exception as e:
+ real_error = extract_real_error(e)
+
+ if is_websocket_disconnect(e):
+ logger.info(f"MCP WebSocket session {session_id} disconnected (wrapped)")
+ else:
+ logger.error(f"MCP WebSocket error for session {session_id}: {real_error}")
+
+ if bridge and not is_websocket_disconnect(e):
+ try:
+ await bridge.send_message(
+ {
+ "type": "error",
+ "error": f"Connection error: {real_error}",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+ )
+ except Exception:
+ pass
+ finally:
+ # Cleanup
+ if session_id in active_sessions:
+ session_info = active_sessions.pop(session_id, None)
+ if session_info:
+ duration = datetime.now(timezone.utc) - session_info["created_at"]
+ logger.info(f"MCP session {session_id} ended after {duration.total_seconds():.2f} seconds")
+
+ if bridge:
+ bridge.stop()
+
+
[email protected]("/ws/connect")
+async def create_mcp_websocket_connection(request: CreateWebSocketConnectionRequest):
+ """Create WebSocket connection URL"""
+ try:
+ session_id = str(uuid.uuid4())
+
+ server_params_json = json.dumps(serialize_for_json(request.server_params.model_dump()))
+ server_params_encoded = base64.b64encode(server_params_json.encode("utf-8")).decode("utf-8")
+
+ return {
+ "status": True,
+ "message": "WebSocket connection URL created",
+ "session_id": session_id,
+ "websocket_url": f"/api/mcp/ws/{session_id}?server_params={server_params_encoded}",
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+
+ except Exception as e:
+ real_error = extract_real_error(e)
+ logger.error(f"Error creating WebSocket connection: {real_error}")
+ return {"status": False, "message": "An internal error occurred while creating the WebSocket connection."}
+
+
[email protected]("/ws/status/{session_id}")
+async def get_mcp_session_status(session_id: str):
+ """Get MCP session status"""
+ session_info = active_sessions.get(session_id)
+
+ if not session_info:
+ return {"status": False, "message": "Session not found", "session_id": session_id}
+
+ # Update last activity
+ active_sessions[session_id]["last_activity"] = datetime.now(timezone.utc)
+
+ return {
+ "status": True,
+ "message": "Session active",
+ "session_id": session_id,
+ "connected": True,
+ "capabilities": session_info.get("capabilities"),
+ "created_at": session_info["created_at"].isoformat(),
+ "last_activity": session_info["last_activity"].isoformat(),
+ }
diff --git a/python/packages/autogen-studio/autogenstudio/web/routes/sessions.py b/python/packages/autogen-studio/autogenstudio/web/routes/sessions.py
index c156fc07a..ea0a0a844 100644
--- a/python/packages/autogen-studio/autogenstudio/web/routes/sessions.py
+++ b/python/packages/autogen-studio/autogenstudio/web/routes/sessions.py
@@ -1,5 +1,4 @@
# api/routes/sessions.py
-import re
from typing import Dict
from fastapi import APIRouter, Depends, HTTPException
diff --git a/python/packages/autogen-studio/frontend/src/components/contentheader.tsx b/python/packages/autogen-studio/frontend/src/components/contentheader.tsx
index 54f3fef89..020969bd6 100644
--- a/python/packages/autogen-studio/frontend/src/components/contentheader.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/contentheader.tsx
@@ -69,7 +69,7 @@ const ContentHeader = ({
<nav aria-label="Breadcrumb" className="flex">
<ol role="list" className="flex items-center space-x-4">
{breadcrumbs.map((page, index) => (
- <li key={page.name}>
+ <li key={index}>
<div className="flex items-center">
{index > 0 && (
<svg
diff --git a/python/packages/autogen-studio/frontend/src/components/header.tsx b/python/packages/autogen-studio/frontend/src/components/header.tsx
index 43fcbc404..503e2ac2a 100644
--- a/python/packages/autogen-studio/frontend/src/components/header.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/header.tsx
@@ -71,7 +71,8 @@ const Header = ({ meta, link }: any) => {
return (
<Disclosure
as="nav"
- className="bg-primary text-primary mb-8 border-b border-secondary"
+ style={{ zIndex: 1000 }}
+ className="bg-primary text-primary z-40 mb-8 border-b border-secondary"
>
{({ open }) => (
<>
diff --git a/python/packages/autogen-studio/frontend/src/components/icons.tsx b/python/packages/autogen-studio/frontend/src/components/icons.tsx
index 4111cc1ab..6e32c41cb 100644
--- a/python/packages/autogen-studio/frontend/src/components/icons.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/icons.tsx
@@ -202,6 +202,19 @@ const Icon = ({ icon = "app", size = 4, className = "" }: Props) => {
</svg>
);
}
+ if (icon === "mcp") {
+ return (
+ <svg
+ className={` ${sizeClass} inline-block `}
+ xmlns="http://www.w3.org/2000/svg"
+ fill="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path d="M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"></path>
+ <path d="M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"></path>
+ </svg>
+ );
+ }
if (icon === "app") {
return (
<svg
diff --git a/python/packages/autogen-studio/frontend/src/components/layout.tsx b/python/packages/autogen-studio/frontend/src/components/layout.tsx
index 5982a7f77..349a9a0fc 100644
--- a/python/packages/autogen-studio/frontend/src/components/layout.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/layout.tsx
@@ -130,3 +130,81 @@ const Layout = ({
};
export default Layout;
+
+// Lite Layout Component for simplified lite mode
+type LiteLayoutProps = {
+ children?: React.ReactNode;
+ showHeader?: boolean;
+ showFooter?: boolean;
+ restricted?: boolean;
+};
+
+export const LiteLayout = ({
+ children,
+ showHeader = true,
+ showFooter = true,
+ restricted = true,
+}: LiteLayoutProps) => {
+ const { darkMode } = React.useContext(appContext);
+ const { authType } = useAuth();
+ const { setHeader } = useConfigStore();
+
+ React.useEffect(() => {
+ document.getElementsByTagName("html")[0].className = `${
+ darkMode === "dark" ? "dark bg-primary" : "light bg-primary"
+ }`;
+ }, [darkMode]);
+
+ // Set up lite mode breadcrumbs and header
+ React.useEffect(() => {
+ setHeader({
+ title: "AutoGen Studio Lite",
+ breadcrumbs: [
+ {
+ name: "Home",
+ href: "/",
+ current: false,
+ },
+ {
+ name: "Lite Mode",
+ href: "/lite",
+ current: true,
+ },
+ ],
+ });
+ }, [setHeader]);
+
+ const layoutContent = (
+ <div className="min-h-screen flex flex-col">
+ {showHeader && (
+ <ContentHeader
+ isMobileMenuOpen={false}
+ onMobileMenuToggle={() => {}} // No mobile menu in lite mode
+ />
+ )}
+
+ <ConfigProvider
+ theme={{
+ token: {
+ borderRadius: 4,
+ colorBgBase: darkMode === "dark" ? "#05080C" : "#ffffff",
+ },
+ algorithm:
+ darkMode === "dark" ? theme.darkAlgorithm : theme.defaultAlgorithm,
+ }}
+ >
+ <main className="flex-1 p-2 text-primary">{children}</main>
+ </ConfigProvider>
+
+ {showFooter && <Footer />}
+ </div>
+ );
+
+ // If page is restricted and auth is not 'none', wrap with ProtectedRoute
+ if (restricted && authType !== "none") {
+ return <ProtectedRoute>{layoutContent}</ProtectedRoute>;
+ }
+
+ // Otherwise, render without protection
+ return layoutContent;
+};
diff --git a/python/packages/autogen-studio/frontend/src/components/shared/AddComponentDropdown.tsx b/python/packages/autogen-studio/frontend/src/components/shared/AddComponentDropdown.tsx
new file mode 100644
index 000000000..a011ee47a
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/shared/AddComponentDropdown.tsx
@@ -0,0 +1,208 @@
+import React from "react";
+import { Button, Dropdown, message } from "antd";
+import { Plus, ChevronDown } from "lucide-react";
+import {
+ Component,
+ ComponentConfig,
+ ComponentTypes,
+ Gallery,
+} from "../types/datamodel";
+import {
+ getTeamTemplatesForDropdown,
+ createTeamFromTemplate,
+ getAgentTemplatesForDropdown,
+ createAgentFromTemplate,
+ getModelTemplatesForDropdown,
+ createModelFromTemplate,
+ getToolTemplatesForDropdown,
+ createToolFromTemplate,
+ getWorkbenchTemplatesForDropdown,
+ createWorkbenchFromTemplate,
+ getTerminationTemplatesForDropdown,
+ createTerminationFromTemplate,
+ type ComponentDropdownOption,
+} from "../types/component-templates";
+
+type CategoryKey =
+ | "teams"
+ | "agents"
+ | "models"
+ | "tools"
+ | "workbenches"
+ | "terminations";
+
+// Helper function to get the correct category key for components
+const getCategoryKey = (componentType: ComponentTypes): CategoryKey => {
+ const mapping: Record<ComponentTypes, CategoryKey> = {
+ team: "teams",
+ agent: "agents",
+ model: "models",
+ tool: "tools",
+ workbench: "workbenches",
+ termination: "terminations",
+ };
+ return mapping[componentType];
+};
+
+interface AddComponentDropdownProps {
+ componentType: ComponentTypes;
+ gallery: Gallery;
+ onComponentAdded: (
+ component: Component<ComponentConfig>,
+ category: CategoryKey
+ ) => void;
+ disabled?: boolean;
+ showIcon?: boolean;
+ showChevron?: boolean;
+ size?: "small" | "middle" | "large";
+ type?: "default" | "primary" | "dashed" | "link" | "text";
+ className?: string;
+ buttonText?: string;
+ // Optional filter for specific component types (useful for MCP workbenches)
+ templateFilter?: (template: ComponentDropdownOption) => boolean;
+}
+
+export const AddComponentDropdown: React.FC<AddComponentDropdownProps> = ({
+ componentType,
+ gallery,
+ onComponentAdded,
+ disabled = false,
+ showIcon = true,
+ showChevron = true,
+ size = "middle",
+ type = "primary",
+ className = "",
+ buttonText,
+ templateFilter,
+}) => {
+ const [messageApi, contextHolder] = message.useMessage();
+
+ // Helper function to get dropdown templates for each component type
+ const getDropdownTemplatesForType = (
+ componentType: ComponentTypes
+ ): ComponentDropdownOption[] => {
+ let templates: ComponentDropdownOption[] = [];
+
+ switch (componentType) {
+ case "team":
+ templates = getTeamTemplatesForDropdown();
+ break;
+ case "agent":
+ templates = getAgentTemplatesForDropdown();
+ break;
+ case "model":
+ templates = getModelTemplatesForDropdown();
+ break;
+ case "tool":
+ templates = getToolTemplatesForDropdown();
+ break;
+ case "workbench":
+ templates = getWorkbenchTemplatesForDropdown();
+ break;
+ case "termination":
+ templates = getTerminationTemplatesForDropdown();
+ break;
+ default:
+ templates = [];
+ }
+
+ // Apply filter if provided
+ if (templateFilter) {
+ templates = templates.filter(templateFilter);
+ }
+
+ return templates;
+ };
+
+ // Generic handler for all component types
+ const handleAddComponentFromTemplate = (
+ componentType: ComponentTypes,
+ templateId: string
+ ) => {
+ const category = getCategoryKey(componentType);
+
+ try {
+ let newComponent: Component<ComponentConfig>;
+
+ switch (componentType) {
+ case "team":
+ newComponent = createTeamFromTemplate(templateId);
+ break;
+ case "agent":
+ newComponent = createAgentFromTemplate(templateId);
+ break;
+ case "model":
+ newComponent = createModelFromTemplate(templateId);
+ break;
+ case "tool":
+ newComponent = createToolFromTemplate(templateId);
+ break;
+ case "workbench":
+ newComponent = createWorkbenchFromTemplate(templateId);
+ break;
+ case "termination":
+ newComponent = createTerminationFromTemplate(templateId);
+ break;
+ default:
+ throw new Error(`Unsupported component type: ${componentType}`);
+ }
+
+ onComponentAdded(newComponent, category);
+ } catch (error) {
+ console.error(`Error creating ${componentType} from template:`, error);
+ messageApi.error(`Failed to create ${componentType}`);
+ }
+ };
+
+ const templates = getDropdownTemplatesForType(componentType);
+
+ // Don't render if no templates available
+ if (templates.length === 0) {
+ return null;
+ }
+
+ const displayButtonText =
+ buttonText ||
+ `Add ${componentType.charAt(0).toUpperCase() + componentType.slice(1)}`;
+
+ return (
+ <>
+ {contextHolder}
+ <Dropdown
+ menu={{
+ items: templates.map((template) => ({
+ key: template.key,
+ label: (
+ <div className="py-1">
+ <div className="font-medium">{template.label}</div>
+ <div className="text-xs text-secondary">
+ {template.description}
+ </div>
+ </div>
+ ),
+ onClick: () =>
+ handleAddComponentFromTemplate(
+ componentType,
+ template.templateId
+ ),
+ })),
+ }}
+ trigger={["click"]}
+ disabled={disabled}
+ >
+ <Button
+ type={type}
+ size={size}
+ icon={showIcon ? <Plus className="w-4 h-4" /> : undefined}
+ disabled={disabled}
+ className={`flex items-center gap-1 ${className}`}
+ >
+ {displayButtonText}
+ {showChevron && <ChevronDown className="w-3 h-3" />}
+ </Button>
+ </Dropdown>
+ </>
+ );
+};
+
+export default AddComponentDropdown;
diff --git a/python/packages/autogen-studio/frontend/src/components/shared/README.md b/python/packages/autogen-studio/frontend/src/components/shared/README.md
new file mode 100644
index 000000000..f0fe0dd20
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/shared/README.md
@@ -0,0 +1,67 @@
+# AddComponentDropdown Usage Examples
+
+The `AddComponentDropdown` component is a reusable dropdown that allows users to add components to a gallery. It supports all component types (teams, agents, models, tools, workbenches, terminations).
+
+## Basic Usage
+
+```tsx
+import { AddComponentDropdown } from "../../shared";
+
+<AddComponentDropdown
+ componentType="workbench"
+ gallery={selectedGallery}
+ onComponentAdded={handleComponentAdded}
+/>;
+```
+
+## Advanced Usage with Filtering (MCP Workbenches)
+
+```tsx
+<AddComponentDropdown
+ componentType="workbench"
+ gallery={selectedGallery}
+ onComponentAdded={handleComponentAdded}
+ size="small"
+ type="text"
+ buttonText="+"
+ showChevron={false}
+ templateFilter={(template) =>
+ template.label.toLowerCase().includes("mcp") ||
+ template.description.toLowerCase().includes("mcp")
+ }
+/>
+```
+
+## Props
+
+- `componentType`: The type of component to add (team, agent, model, tool, workbench, termination)
+- `gallery`: The gallery to add the component to
+- `onComponentAdded`: Callback when a component is added
+- `disabled`: Whether the dropdown is disabled
+- `showIcon`: Whether to show the plus icon
+- `showChevron`: Whether to show the chevron down icon
+- `size`: Button size
+- `type`: Button type
+- `className`: Additional CSS classes
+- `buttonText`: Custom button text
+- `templateFilter`: Optional filter function for templates
+
+## Handler Signature
+
+```tsx
+const handleComponentAdded = (
+ component: Component<ComponentConfig>,
+ category: CategoryKey
+) => {
+ // Handle the added component
+ // Update your gallery/state here
+};
+```
+
+## Benefits
+
+1. **Reusability**: Use the same component across different views
+2. **Consistency**: Same UI/UX everywhere
+3. **Maintainability**: Single source of truth for component addition logic
+4. **Flexibility**: Configurable with props and filters
+5. **Type Safety**: Fully typed with TypeScript
diff --git a/python/packages/autogen-studio/frontend/src/components/shared/index.ts b/python/packages/autogen-studio/frontend/src/components/shared/index.ts
new file mode 100644
index 000000000..1690f40b6
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/shared/index.ts
@@ -0,0 +1 @@
+export { AddComponentDropdown } from "./AddComponentDropdown";
diff --git a/python/packages/autogen-studio/frontend/src/components/sidebar.tsx b/python/packages/autogen-studio/frontend/src/components/sidebar.tsx
index c27aaf79b..8a3ea2be2 100644
--- a/python/packages/autogen-studio/frontend/src/components/sidebar.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/sidebar.tsx
@@ -42,6 +42,14 @@ const navigation: INavItem[] = [
icon: MessagesSquare,
breadcrumbs: [{ name: "Playground", href: "/", current: true }],
},
+ {
+ name: "MCP (Experimental)",
+ href: "/mcp",
+ icon: ({ className }: { className?: string }) => (
+ <Icon size={6} icon="mcp" className={className} />
+ ),
+ breadcrumbs: [{ name: "MCP (Experimental)", href: "/mcp", current: true }],
+ },
{
name: "Gallery",
href: "/gallery",
diff --git a/python/packages/autogen-studio/frontend/src/components/types/component-templates.ts b/python/packages/autogen-studio/frontend/src/components/types/component-templates.ts
new file mode 100644
index 000000000..4372ad20b
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/types/component-templates.ts
@@ -0,0 +1,698 @@
+import {
+ Component,
+ ComponentConfig,
+ ComponentTypes,
+ TeamConfig,
+ AgentConfig,
+ ModelConfig,
+ ToolConfig,
+ WorkbenchConfig,
+ TerminationConfig,
+ SelectorGroupChatConfig,
+ RoundRobinGroupChatConfig,
+ AssistantAgentConfig,
+ UserProxyAgentConfig,
+ MultimodalWebSurferConfig,
+ OpenAIClientConfig,
+ AzureOpenAIClientConfig,
+ AnthropicClientConfig,
+ FunctionToolConfig,
+ PythonCodeExecutionToolConfig,
+ StaticWorkbenchConfig,
+ McpWorkbenchConfig,
+ StdioServerParams,
+ SseServerParams,
+ StreamableHttpServerParams,
+ MaxMessageTerminationConfig,
+ TextMentionTerminationConfig,
+ StopMessageTerminationConfig,
+ TokenUsageTerminationConfig,
+ HandoffTerminationConfig,
+ TimeoutTerminationConfig,
+ ExternalTerminationConfig,
+ SourceMatchTerminationConfig,
+ TextMessageTerminationConfig,
+ OrTerminationConfig,
+ AndTerminationConfig,
+} from "./datamodel";
+import { PROVIDERS } from "./guards";
+
+// Template interface for component types
+export interface ComponentTemplate<T extends ComponentConfig> {
+ id: string;
+ label: string;
+ description: string;
+ provider: string;
+ component_type: ComponentTypes;
+ config: T;
+ version?: number;
+ component_version?: number;
+}
+
+// Team Templates
+export const TEAM_TEMPLATES: ComponentTemplate<TeamConfig>[] = [
+ {
+ id: "round-robin-team",
+ label: "Round Robin Team",
+ description: "A team where agents take turns in a fixed order",
+ provider: PROVIDERS.ROUND_ROBIN_TEAM,
+ component_type: "team",
+ version: 1,
+ component_version: 1,
+ config: {
+ participants: [],
+ termination_condition: {
+ provider: PROVIDERS.TEXT_MENTION,
+ component_type: "termination",
+ config: { text: "TERMINATE" },
+ },
+ max_turns: 10,
+ } as RoundRobinGroupChatConfig,
+ },
+ {
+ id: "selector-team",
+ label: "Selector Team",
+ description: "A team with a model that selects which agent speaks next",
+ provider: PROVIDERS.SELECTOR_TEAM,
+ component_type: "team",
+ version: 1,
+ component_version: 1,
+ config: {
+ participants: [],
+ model_client: {
+ provider: PROVIDERS.OPENAI,
+ component_type: "model",
+ config: { model: "gpt-4o-mini" },
+ },
+ termination_condition: {
+ provider: PROVIDERS.TEXT_MENTION,
+ component_type: "termination",
+ config: { text: "TERMINATE" },
+ },
+ max_turns: 10,
+ selector_prompt:
+ "Select the next speaker based on the conversation context and task requirements.",
+ allow_repeated_speaker: true,
+ } as SelectorGroupChatConfig,
+ },
+];
+
+// Agent Templates
+export const AGENT_TEMPLATES: ComponentTemplate<AgentConfig>[] = [
+ {
+ id: "assistant-agent",
+ label: "Assistant Agent",
+ description: "A helpful AI assistant with tool capabilities",
+ provider: PROVIDERS.ASSISTANT_AGENT,
+ component_type: "agent",
+ version: 2,
+ component_version: 2,
+ config: {
+ name: "assistant_agent",
+ description:
+ "A helpful AI assistant that can use tools to solve problems",
+ system_message:
+ "You are a helpful assistant. Solve tasks carefully and methodically. When you have completed the task, say TERMINATE.",
+ model_client: {
+ provider: PROVIDERS.OPENAI,
+ component_type: "model",
+ config: { model: "gpt-4o-mini" },
+ },
+ workbench: [],
+ // model_context is optional and complex, omit for now
+ reflect_on_tool_use: false,
+ tool_call_summary_format: "{result}",
+ model_client_stream: false,
+ } as AssistantAgentConfig,
+ },
+ {
+ id: "user-proxy-agent",
+ label: "User Proxy Agent",
+ description: "An agent that represents human input and interaction",
+ provider: PROVIDERS.USER_PROXY,
+ component_type: "agent",
+ version: 1,
+ component_version: 1,
+ config: {
+ name: "user_proxy",
+ description: "A human user proxy for providing input and feedback",
+ } as UserProxyAgentConfig,
+ },
+ {
+ id: "web-surfer-agent",
+ label: "Web Surfer Agent",
+ description: "An agent that can browse and interact with web pages",
+ provider: PROVIDERS.WEB_SURFER,
+ component_type: "agent",
+ version: 1,
+ component_version: 1,
+ config: {
+ name: "web_surfer",
+ description:
+ "An agent that can browse the web and interact with web pages",
+ model_client: {
+ provider: PROVIDERS.OPENAI,
+ component_type: "model",
+ config: { model: "gpt-4o" }, // Web surfer needs vision capabilities
+ },
+ headless: true,
+ start_page: "https://www.google.com",
+ animate_actions: false,
+ to_save_screenshots: false,
+ use_ocr: false,
+ to_resize_viewport: true,
+ } as MultimodalWebSurferConfig,
+ },
+];
+
+// Model Templates
+export const MODEL_TEMPLATES: ComponentTemplate<ModelConfig>[] = [
+ {
+ id: "openai-gpt-4o-mini",
+ label: "OpenAI GPT-4o Mini",
+ description: "Fast and cost-effective OpenAI model for most tasks",
+ provider: PROVIDERS.OPENAI,
+ component_type: "model",
+ version: 1,
+ component_version: 1,
+ config: {
+ model: "gpt-4o-mini",
+ temperature: 0.7,
+ max_tokens: 4096,
+ } as OpenAIClientConfig,
+ },
+ {
+ id: "openai-gpt-4o",
+ label: "OpenAI GPT-4o",
+ description: "Advanced OpenAI model with vision and advanced reasoning",
+ provider: PROVIDERS.OPENAI,
+ component_type: "model",
+ version: 1,
+ component_version: 1,
+ config: {
+ model: "gpt-4o",
+ temperature: 0.7,
+ max_tokens: 4096,
+ } as OpenAIClientConfig,
+ },
+ {
+ id: "azure-openai-gpt-4o-mini",
+ label: "Azure OpenAI GPT-4o Mini",
+ description: "Azure-hosted OpenAI model for enterprise use",
+ provider: PROVIDERS.AZURE_OPENAI,
+ component_type: "model",
+ version: 1,
+ component_version: 1,
+ config: {
+ model: "gpt-4o-mini",
+ azure_endpoint: "https://your-endpoint.openai.azure.com/",
+ azure_deployment: "gpt-4o-mini",
+ api_version: "2024-06-01",
+ temperature: 0.7,
+ max_tokens: 4096,
+ } as AzureOpenAIClientConfig,
+ },
+ {
+ id: "anthropic-claude-3-sonnet",
+ label: "Anthropic Claude-3 Sonnet",
+ description: "Anthropic's balanced model for reasoning and creativity",
+ provider: PROVIDERS.ANTHROPIC,
+ component_type: "model",
+ version: 1,
+ component_version: 1,
+ config: {
+ model: "claude-3-5-sonnet-20241022",
+ max_tokens: 4096,
+ temperature: 0.7,
+ } as AnthropicClientConfig,
+ },
+];
+
+// Tool Templates
+export const TOOL_TEMPLATES: ComponentTemplate<ToolConfig>[] = [
+ {
+ id: "function-tool",
+ label: "Function Tool",
+ description: "A custom Python function that can be called by agents",
+ provider: PROVIDERS.FUNCTION_TOOL,
+ component_type: "tool",
+ version: 1,
+ component_version: 1,
+ config: {
+ name: "my_function",
+ description: "A custom function that performs a specific task",
+ source_code: `def my_function(input_text: str) -> str:
+ """
+ A template function that processes input text.
+
+ Args:
+ input_text: The text to process
+
+ Returns:
+ Processed text result
+ """
+ # Replace this with your custom function logic
+ result = f"Processed: {input_text}"
+ return result`,
+ global_imports: [],
+ has_cancellation_support: false,
+ } as FunctionToolConfig,
+ },
+ {
+ id: "code-execution-tool",
+ label: "Code Execution Tool",
+ description: "Execute Python code in a secure environment",
+ provider: PROVIDERS.PYTHON_CODE_EXECUTION_TOOL,
+ component_type: "tool",
+ version: 1,
+ component_version: 1,
+ config: {
+ executor: {
+ provider:
+ "autogen_ext.code_executors.local.LocalCommandLineCodeExecutor",
+ config: {
+ timeout: 60,
+ work_dir: "./coding",
+ functions_module: "functions",
+ cleanup_temp_files: true,
+ },
+ },
+ description: "Execute Python code in a secure environment",
+ name: "code_execution",
+ } as PythonCodeExecutionToolConfig,
+ },
+];
+
+// Workbench Templates
+export const WORKBENCH_TEMPLATES: ComponentTemplate<WorkbenchConfig>[] = [
+ {
+ id: "static-workbench",
+ label: "Static Workbench",
+ description: "A workbench with a collection of tools",
+ provider: PROVIDERS.STATIC_WORKBENCH,
+ component_type: "workbench",
+ version: 1,
+ component_version: 1,
+ config: {
+ tools: [],
+ } as StaticWorkbenchConfig,
+ },
+ {
+ id: "mcp-stdio-workbench",
+ label: "MCP Stdio Server",
+ description: "Model Context Protocol server via command line",
+ provider: PROVIDERS.MCP_WORKBENCH,
+ component_type: "workbench",
+ version: 1,
+ component_version: 1,
+ config: {
+ server_params: {
+ type: "StdioServerParams",
+ command: "npx",
+ args: ["@modelcontextprotocol/server-everything"],
+ env: {},
+ read_timeout_seconds: 30,
+ } as StdioServerParams,
+ } as McpWorkbenchConfig,
+ },
+ {
+ id: "mcp-sse-workbench",
+ label: "MCP SSE Server",
+ description: "Model Context Protocol server via server-sent events",
+ provider: PROVIDERS.MCP_WORKBENCH,
+ component_type: "workbench",
+ version: 1,
+ component_version: 1,
+ config: {
+ server_params: {
+ type: "SseServerParams",
+ url: "http://localhost:3001/sse",
+ headers: {
+ Authorization: "Bearer your-token-here",
+ },
+ timeout: 30,
+ sse_read_timeout: 30,
+ } as SseServerParams,
+ } as McpWorkbenchConfig,
+ },
+ {
+ id: "mcp-http-workbench",
+ label: "MCP HTTP Server",
+ description: "Model Context Protocol server via streamable HTTP",
+ provider: PROVIDERS.MCP_WORKBENCH,
+ component_type: "workbench",
+ version: 1,
+ component_version: 1,
+ config: {
+ server_params: {
+ type: "StreamableHttpServerParams",
+ url: "http://localhost:3001/mcp",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: "Bearer your-token-here",
+ },
+ timeout: 30,
+ sse_read_timeout: 30,
+ terminate_on_close: true,
+ } as StreamableHttpServerParams,
+ } as McpWorkbenchConfig,
+ },
+];
+
+// Termination Templates
+export const TERMINATION_TEMPLATES: ComponentTemplate<TerminationConfig>[] = [
+ {
+ id: "text-mention-termination",
+ label: "Text Mention Termination",
+ description: "Terminate when a specific text is mentioned",
+ provider: PROVIDERS.TEXT_MENTION,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {
+ text: "TERMINATE",
+ } as TextMentionTerminationConfig,
+ },
+ {
+ id: "max-message-termination",
+ label: "Max Message Termination",
+ description: "Terminate after a maximum number of messages",
+ provider: PROVIDERS.MAX_MESSAGE,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {
+ max_messages: 10,
+ include_agent_event: false,
+ } as MaxMessageTerminationConfig,
+ },
+ {
+ id: "stop-message-termination",
+ label: "Stop Message Termination",
+ description: "Terminate when a StopMessage is received",
+ provider: PROVIDERS.STOP_MESSAGE,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {} as StopMessageTerminationConfig,
+ },
+ {
+ id: "token-usage-termination",
+ label: "Token Usage Termination",
+ description: "Terminate when token usage limits are reached",
+ provider: PROVIDERS.TOKEN_USAGE,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {
+ max_total_token: 1000,
+ } as TokenUsageTerminationConfig,
+ },
+ {
+ id: "timeout-termination",
+ label: "Timeout Termination",
+ description: "Terminate after a specified duration",
+ provider: PROVIDERS.TIMEOUT,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {
+ timeout_seconds: 300,
+ } as TimeoutTerminationConfig,
+ },
+ {
+ id: "handoff-termination",
+ label: "Handoff Termination",
+ description: "Terminate when handoff to specific target is detected",
+ provider: PROVIDERS.HANDOFF,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {
+ target: "user",
+ } as HandoffTerminationConfig,
+ },
+ {
+ id: "source-match-termination",
+ label: "Source Match Termination",
+ description: "Terminate when specific sources respond",
+ provider: PROVIDERS.SOURCE_MATCH,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {
+ sources: ["agent1"],
+ } as SourceMatchTerminationConfig,
+ },
+ {
+ id: "text-message-termination",
+ label: "Text Message Termination",
+ description: "Terminate when a TextMessage is received",
+ provider: PROVIDERS.TEXT_MESSAGE,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {
+ source: undefined,
+ } as TextMessageTerminationConfig,
+ },
+ {
+ id: "external-termination",
+ label: "External Termination",
+ description: "Terminate when externally controlled by calling set() method",
+ provider: PROVIDERS.EXTERNAL,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {} as ExternalTerminationConfig,
+ },
+ {
+ id: "or-termination",
+ label: "OR Termination",
+ description: "Terminate when any of the conditions are met",
+ provider: PROVIDERS.OR_TERMINATION,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {
+ conditions: [
+ {
+ provider: PROVIDERS.TEXT_MENTION,
+ component_type: "termination",
+ config: { text: "TERMINATE" },
+ },
+ {
+ provider: PROVIDERS.MAX_MESSAGE,
+ component_type: "termination",
+ config: { max_messages: 20 },
+ },
+ ],
+ } as OrTerminationConfig,
+ },
+ {
+ id: "and-termination",
+ label: "AND Termination",
+ description: "Terminate when all conditions are met",
+ provider: PROVIDERS.AND_TERMINATION,
+ component_type: "termination",
+ version: 1,
+ component_version: 1,
+ config: {
+ conditions: [
+ {
+ provider: PROVIDERS.TEXT_MENTION,
+ component_type: "termination",
+ config: { text: "TASK_COMPLETE" },
+ },
+ {
+ provider: PROVIDERS.MAX_MESSAGE,
+ component_type: "termination",
+ config: { max_messages: 5 },
+ },
+ ],
+ } as AndTerminationConfig,
+ },
+];
+
+// Main template registry
+export const COMPONENT_TEMPLATES = {
+ team: TEAM_TEMPLATES,
+ agent: AGENT_TEMPLATES,
+ model: MODEL_TEMPLATES,
+ tool: TOOL_TEMPLATES,
+ workbench: WORKBENCH_TEMPLATES,
+ termination: TERMINATION_TEMPLATES,
+} as const;
+
+// Helper functions
+export function getTemplatesForType<T extends ComponentTypes>(
+ componentType: T
+): ComponentTemplate<ComponentConfig>[] {
+ return COMPONENT_TEMPLATES[componentType] || [];
+}
+
+export function getTemplateById(
+ componentType: ComponentTypes,
+ templateId: string
+): ComponentTemplate<ComponentConfig> | undefined {
+ const templates = COMPONENT_TEMPLATES[componentType];
+ return templates.find((template) => template.id === templateId);
+}
+
+export function getDefaultTemplate(
+ componentType: ComponentTypes
+): ComponentTemplate<ComponentConfig> | undefined {
+ const templates = COMPONENT_TEMPLATES[componentType];
+ return templates[0]; // Return first template as default
+}
+
+export function createComponentFromTemplate(
+ templateId: string,
+ componentType: ComponentTypes,
+ overrides?: Partial<Component<ComponentConfig>>
+): Component<ComponentConfig> {
+ const template = getTemplateById(componentType, templateId);
+ if (!template) {
+ throw new Error(
+ `Template ${templateId} not found for component type ${componentType}`
+ );
+ }
+
+ return {
+ provider: template.provider,
+ component_type: template.component_type,
+ version: template.version,
+ component_version: template.component_version,
+ description: template.description,
+ config: template.config,
+ label: template.label,
+ ...overrides,
+ };
+}
+
+// Workbench-specific helper functions
+export interface WorkbenchDropdownOption {
+ key: string;
+ label: string;
+ description: string;
+ templateId: string;
+}
+
+export function getWorkbenchTemplatesForDropdown(): WorkbenchDropdownOption[] {
+ return WORKBENCH_TEMPLATES.map((template) => ({
+ key: template.id,
+ label: template.label,
+ description: template.description,
+ templateId: template.id,
+ }));
+}
+
+export function createWorkbenchFromTemplate(
+ templateId: string,
+ customLabel?: string
+): Component<ComponentConfig> {
+ const template = getTemplateById("workbench", templateId);
+ if (!template) {
+ throw new Error(`Workbench template ${templateId} not found`);
+ }
+
+ return createComponentFromTemplate(templateId, "workbench", {
+ label: customLabel || `New ${template.label}`,
+ });
+}
+
+// Generic dropdown option interface
+export interface ComponentDropdownOption {
+ key: string;
+ label: string;
+ description: string;
+ templateId: string;
+}
+
+// Generic helper functions for all component types
+export function getTemplatesForDropdown(
+ componentType: ComponentTypes
+): ComponentDropdownOption[] {
+ const templates = getTemplatesForType(componentType);
+ return templates.map((template) => ({
+ key: template.id,
+ label: template.label,
+ description: template.description,
+ templateId: template.id,
+ }));
+}
+
+export function createComponentFromTemplateById(
+ componentType: ComponentTypes,
+ templateId: string,
+ customLabel?: string
+): Component<ComponentConfig> {
+ const template = getTemplateById(componentType, templateId);
+ if (!template) {
+ throw new Error(`${componentType} template ${templateId} not found`);
+ }
+
+ return createComponentFromTemplate(templateId, componentType, {
+ label: customLabel || `New ${template.label}`,
+ });
+}
+
+// Specific helper functions for each component type
+export function getTeamTemplatesForDropdown(): ComponentDropdownOption[] {
+ return getTemplatesForDropdown("team");
+}
+
+export function createTeamFromTemplate(
+ templateId: string,
+ customLabel?: string
+): Component<ComponentConfig> {
+ return createComponentFromTemplateById("team", templateId, customLabel);
+}
+
+export function getAgentTemplatesForDropdown(): ComponentDropdownOption[] {
+ return getTemplatesForDropdown("agent");
+}
+
+export function createAgentFromTemplate(
+ templateId: string,
+ customLabel?: string
+): Component<ComponentConfig> {
+ return createComponentFromTemplateById("agent", templateId, customLabel);
+}
+
+export function getModelTemplatesForDropdown(): ComponentDropdownOption[] {
+ return getTemplatesForDropdown("model");
+}
+
+export function createModelFromTemplate(
+ templateId: string,
+ customLabel?: string
+): Component<ComponentConfig> {
+ return createComponentFromTemplateById("model", templateId, customLabel);
+}
+
+export function getToolTemplatesForDropdown(): ComponentDropdownOption[] {
+ return getTemplatesForDropdown("tool");
+}
+
+export function createToolFromTemplate(
+ templateId: string,
+ customLabel?: string
+): Component<ComponentConfig> {
+ return createComponentFromTemplateById("tool", templateId, customLabel);
+}
+
+export function getTerminationTemplatesForDropdown(): ComponentDropdownOption[] {
+ return getTemplatesForDropdown("termination");
+}
+
+export function createTerminationFromTemplate(
+ templateId: string,
+ customLabel?: string
+): Component<ComponentConfig> {
+ return createComponentFromTemplateById(
+ "termination",
+ templateId,
+ customLabel
+ );
+}
diff --git a/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts b/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts
index 46482e80c..a6bdfe4ff 100644
--- a/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts
+++ b/python/packages/autogen-studio/frontend/src/components/types/datamodel.ts
@@ -5,7 +5,8 @@ export type ComponentTypes =
| "agent"
| "model"
| "tool"
- | "termination";
+ | "termination"
+ | "workbench";
export interface Component<T extends ComponentConfig> {
provider: string;
component_type: ComponentTypes;
@@ -17,7 +18,20 @@ export interface Component<T extends ComponentConfig> {
}
// Message Types
-export interface RequestUsage {
+export type TerminationConfig =
+ | OrTerminationConfig
+ | AndTerminationConfig
+ | MaxMessageTerminationConfig
+ | TextMentionTerminationConfig
+ | StopMessageTerminationConfig
+ | TokenUsageTerminationConfig
+ | HandoffTerminationConfig
+ | TimeoutTerminationConfig
+ | ExternalTerminationConfig
+ | SourceMatchTerminationConfig
+ | TextMessageTerminationConfig;
+
+interface RequestUsage {
prompt_tokens: number;
completion_tokens: number;
}
@@ -128,11 +142,16 @@ export interface JupyterCodeExecutorConfig extends CodeExecutorBaseConfig {
// Python Code Execution Tool Config
export interface PythonCodeExecutionToolConfig {
- executor: Component<
- | LocalCommandLineCodeExecutorConfig
- | DockerCommandLineCodeExecutorConfig
- | JupyterCodeExecutorConfig
- >;
+ executor: {
+ provider: string;
+ config:
+ | LocalCommandLineCodeExecutorConfig
+ | DockerCommandLineCodeExecutorConfig
+ | JupyterCodeExecutorConfig;
+ version?: number;
+ component_version?: number;
+ description?: string | null;
+ };
description?: string;
name?: string;
}
@@ -146,6 +165,45 @@ export interface FunctionToolConfig {
has_cancellation_support: boolean;
}
+// Workbench Configs
+export interface StaticWorkbenchConfig {
+ tools: Component<ToolConfig>[];
+}
+
+export interface StdioServerParams {
+ type: "StdioServerParams";
+ command: string;
+ args?: string[];
+ env?: Record<string, string>;
+ read_timeout_seconds?: number;
+}
+
+export interface SseServerParams {
+ type: "SseServerParams";
+ url: string;
+ headers?: Record<string, any>;
+ timeout?: number;
+ sse_read_timeout?: number;
+}
+
+export interface StreamableHttpServerParams {
+ type: "StreamableHttpServerParams";
+ url: string;
+ headers?: Record<string, any>;
+ timeout?: number;
+ sse_read_timeout?: number;
+ terminate_on_close?: boolean;
+}
+
+export type McpServerParams =
+ | StdioServerParams
+ | SseServerParams
+ | StreamableHttpServerParams;
+
+export interface McpWorkbenchConfig {
+ server_params: McpServerParams;
+}
+
// Provider-based Configs
export interface SelectorGroupChatConfig {
participants: Component<AgentConfig>[];
@@ -162,6 +220,13 @@ export interface RoundRobinGroupChatConfig {
max_turns?: number;
}
+export interface SwarmConfig {
+ participants: Component<AgentConfig>[];
+ termination_condition?: Component<TerminationConfig>;
+ max_turns?: number;
+ emit_team_events?: boolean;
+}
+
export interface MultimodalWebSurferConfig {
name: string;
model_client: Component<ModelConfig>;
@@ -181,7 +246,7 @@ export interface MultimodalWebSurferConfig {
export interface AssistantAgentConfig {
name: string;
model_client: Component<ModelConfig>;
- tools?: Component<ToolConfig>[];
+ workbench?: Component<WorkbenchConfig>[] | Component<WorkbenchConfig>;
handoffs?: any[]; // HandoffBase | str equivalent
model_context?: Component<ChatCompletionContextConfig>;
description: string;
@@ -277,14 +342,49 @@ export interface AndTerminationConfig {
export interface MaxMessageTerminationConfig {
max_messages: number;
+ include_agent_event?: boolean;
}
export interface TextMentionTerminationConfig {
text: string;
}
+// Additional termination configs
+export interface StopMessageTerminationConfig {
+ // No additional config needed
+}
+
+export interface TokenUsageTerminationConfig {
+ max_total_token?: number;
+ max_prompt_token?: number;
+ max_completion_token?: number;
+}
+
+export interface HandoffTerminationConfig {
+ target: string;
+}
+
+export interface TimeoutTerminationConfig {
+ timeout_seconds: number;
+}
+
+export interface ExternalTerminationConfig {
+ // No additional config needed
+}
+
+export interface SourceMatchTerminationConfig {
+ sources: string[];
+}
+
+export interface TextMessageTerminationConfig {
+ source?: string;
+}
+
// Config type unions based on provider
-export type TeamConfig = SelectorGroupChatConfig | RoundRobinGroupChatConfig;
+export type TeamConfig =
+ | SelectorGroupChatConfig
+ | RoundRobinGroupChatConfig
+ | SwarmConfig;
export type AgentConfig =
| MultimodalWebSurferConfig
@@ -298,19 +398,16 @@ export type ModelConfig =
export type ToolConfig = FunctionToolConfig | PythonCodeExecutionToolConfig;
-export type ChatCompletionContextConfig = UnboundedChatCompletionContextConfig;
+export type WorkbenchConfig = StaticWorkbenchConfig | McpWorkbenchConfig;
-export type TerminationConfig =
- | OrTerminationConfig
- | AndTerminationConfig
- | MaxMessageTerminationConfig
- | TextMentionTerminationConfig;
+export type ChatCompletionContextConfig = UnboundedChatCompletionContextConfig;
export type ComponentConfig =
| TeamConfig
| AgentConfig
| ModelConfig
| ToolConfig
+ | WorkbenchConfig
| TerminationConfig
| ChatCompletionContextConfig;
@@ -409,6 +506,7 @@ export interface UISettings {
show_llm_call_events: boolean;
expanded_messages_by_default?: boolean;
show_agent_flow_by_default?: boolean;
+ human_input_timeout_minutes?: number; // 1-30 minutes, defaults to 3
// You can add more UI settings here as needed
}
@@ -445,6 +543,7 @@ export interface GalleryConfig {
agents: Component<AgentConfig>[];
models: Component<ModelConfig>[];
tools: Component<ToolConfig>[];
+ workbenches: Component<WorkbenchConfig>[];
terminations: Component<TerminationConfig>[];
};
}
diff --git a/python/packages/autogen-studio/frontend/src/components/types/guards.ts b/python/packages/autogen-studio/frontend/src/components/types/guards.ts
index 6e26d100b..f3e0413a3 100644
--- a/python/packages/autogen-studio/frontend/src/components/types/guards.ts
+++ b/python/packages/autogen-studio/frontend/src/components/types/guards.ts
@@ -5,19 +5,32 @@ import type {
AgentConfig,
ModelConfig,
ToolConfig,
+ WorkbenchConfig,
TerminationConfig,
ChatCompletionContextConfig,
SelectorGroupChatConfig,
RoundRobinGroupChatConfig,
+ SwarmConfig,
MultimodalWebSurferConfig,
AssistantAgentConfig,
UserProxyAgentConfig,
OpenAIClientConfig,
AzureOpenAIClientConfig,
FunctionToolConfig,
+ PythonCodeExecutionToolConfig,
+ LocalCommandLineCodeExecutorConfig,
+ StaticWorkbenchConfig,
+ McpWorkbenchConfig,
OrTerminationConfig,
MaxMessageTerminationConfig,
TextMentionTerminationConfig,
+ StopMessageTerminationConfig,
+ TokenUsageTerminationConfig,
+ HandoffTerminationConfig,
+ TimeoutTerminationConfig,
+ ExternalTerminationConfig,
+ SourceMatchTerminationConfig,
+ TextMessageTerminationConfig,
UnboundedChatCompletionContextConfig,
AnthropicClientConfig,
AndTerminationConfig,
@@ -28,6 +41,7 @@ const PROVIDERS = {
// Teams
ROUND_ROBIN_TEAM: "autogen_agentchat.teams.RoundRobinGroupChat",
SELECTOR_TEAM: "autogen_agentchat.teams.SelectorGroupChat",
+ SWARM_TEAM: "autogen_agentchat.teams.Swarm",
// Agents
ASSISTANT_AGENT: "autogen_agentchat.agents.AssistantAgent",
@@ -41,12 +55,30 @@ const PROVIDERS = {
// Tools
FUNCTION_TOOL: "autogen_core.tools.FunctionTool",
+ PYTHON_CODE_EXECUTION_TOOL:
+ "autogen_ext.tools.code_execution.PythonCodeExecutionTool",
+
+ // Code Executors
+ LOCAL_COMMAND_LINE_CODE_EXECUTOR:
+ "autogen_ext.code_executors.local.LocalCommandLineCodeExecutor",
+
+ // Workbenches
+ STATIC_WORKBENCH: "autogen_core.tools.StaticWorkbench",
+ STATIC_STREAM_WORKBENCH: "autogen_core.tools.StaticStreamWorkbench",
+ MCP_WORKBENCH: "autogen_ext.tools.mcp.McpWorkbench",
// Termination
OR_TERMINATION: "autogen_agentchat.base.OrTerminationCondition",
AND_TERMINATION: "autogen_agentchat.base.AndTerminationCondition",
MAX_MESSAGE: "autogen_agentchat.conditions.MaxMessageTermination",
TEXT_MENTION: "autogen_agentchat.conditions.TextMentionTermination",
+ STOP_MESSAGE: "autogen_agentchat.conditions.StopMessageTermination",
+ TOKEN_USAGE: "autogen_agentchat.conditions.TokenUsageTermination",
+ HANDOFF: "autogen_agentchat.conditions.HandoffTermination",
+ TIMEOUT: "autogen_agentchat.conditions.TimeoutTermination",
+ EXTERNAL: "autogen_agentchat.conditions.ExternalTermination",
+ SOURCE_MATCH: "autogen_agentchat.conditions.SourceMatchTermination",
+ TEXT_MESSAGE: "autogen_agentchat.conditions.TextMessageTermination",
// Contexts
UNBOUNDED_CONTEXT:
@@ -60,6 +92,7 @@ type ProviderToConfig = {
// Teams
[PROVIDERS.SELECTOR_TEAM]: SelectorGroupChatConfig;
[PROVIDERS.ROUND_ROBIN_TEAM]: RoundRobinGroupChatConfig;
+ [PROVIDERS.SWARM_TEAM]: SwarmConfig;
[PROVIDERS.ANTHROPIC]: AnthropicClientConfig;
// Agents
@@ -73,12 +106,28 @@ type ProviderToConfig = {
// Tools
[PROVIDERS.FUNCTION_TOOL]: FunctionToolConfig;
+ [PROVIDERS.PYTHON_CODE_EXECUTION_TOOL]: PythonCodeExecutionToolConfig;
+
+ // Code Executors
+ [PROVIDERS.LOCAL_COMMAND_LINE_CODE_EXECUTOR]: LocalCommandLineCodeExecutorConfig;
+
+ // Workbenches
+ [PROVIDERS.STATIC_WORKBENCH]: StaticWorkbenchConfig;
+ [PROVIDERS.STATIC_STREAM_WORKBENCH]: StaticWorkbenchConfig;
+ [PROVIDERS.MCP_WORKBENCH]: McpWorkbenchConfig;
// Termination
[PROVIDERS.OR_TERMINATION]: OrTerminationConfig;
[PROVIDERS.AND_TERMINATION]: AndTerminationConfig;
[PROVIDERS.MAX_MESSAGE]: MaxMessageTerminationConfig;
[PROVIDERS.TEXT_MENTION]: TextMentionTerminationConfig;
+ [PROVIDERS.STOP_MESSAGE]: StopMessageTerminationConfig;
+ [PROVIDERS.TOKEN_USAGE]: TokenUsageTerminationConfig;
+ [PROVIDERS.HANDOFF]: HandoffTerminationConfig;
+ [PROVIDERS.TIMEOUT]: TimeoutTerminationConfig;
+ [PROVIDERS.EXTERNAL]: ExternalTerminationConfig;
+ [PROVIDERS.SOURCE_MATCH]: SourceMatchTerminationConfig;
+ [PROVIDERS.TEXT_MESSAGE]: TextMessageTerminationConfig;
// Contexts
[PROVIDERS.UNBOUNDED_CONTEXT]: UnboundedChatCompletionContextConfig;
@@ -125,6 +174,8 @@ export function isModelComponent(
return component.component_type === "model";
}
+// NOTE: Tools are now deprecated - use workbenches instead
+// This guard is kept for backward compatibility during migration
export function isToolComponent(
component: Component<ComponentConfig>
): component is Component<ToolConfig> {
@@ -156,6 +207,12 @@ export function isSelectorTeam(
return isComponentOfType(component, PROVIDERS.SELECTOR_TEAM);
}
+export function isSwarmTeam(
+ component: Component<ComponentConfig>
+): component is Component<SwarmConfig> {
+ return isComponentOfType(component, PROVIDERS.SWARM_TEAM);
+}
+
// Agent provider guards with proper type narrowing
export function isAssistantAgent(
component: Component<ComponentConfig>
@@ -200,6 +257,37 @@ export function isFunctionTool(
return isComponentOfType(component, PROVIDERS.FUNCTION_TOOL);
}
+// Workbench provider guards with proper type narrowing
+export function isStaticWorkbench(
+ component: Component<ComponentConfig> | null | undefined
+): component is Component<StaticWorkbenchConfig> {
+ return (
+ !!component && isComponentOfType(component, PROVIDERS.STATIC_WORKBENCH)
+ );
+}
+
+export function isStaticStreamWorkbench(
+ component: Component<ComponentConfig> | null | undefined
+): component is Component<StaticWorkbenchConfig> {
+ return (
+ !!component &&
+ isComponentOfType(component, PROVIDERS.STATIC_STREAM_WORKBENCH)
+ );
+}
+
+// Combined guard for both static workbench types
+export function isAnyStaticWorkbench(
+ component: Component<ComponentConfig> | null | undefined
+): component is Component<StaticWorkbenchConfig> {
+ return isStaticWorkbench(component) || isStaticStreamWorkbench(component);
+}
+
+export function isMcpWorkbench(
+ component: Component<ComponentConfig> | null | undefined
+): component is Component<McpWorkbenchConfig> {
+ return !!component && isComponentOfType(component, PROVIDERS.MCP_WORKBENCH);
+}
+
// Termination provider guards with proper type narrowing
export function isOrTermination(
component: Component<ComponentConfig>
@@ -235,6 +323,48 @@ export function isTextMentionTermination(
return isComponentOfType(component, PROVIDERS.TEXT_MENTION);
}
+export function isStopMessageTermination(
+ component: Component<ComponentConfig>
+): component is Component<StopMessageTerminationConfig> {
+ return isComponentOfType(component, PROVIDERS.STOP_MESSAGE);
+}
+
+export function isTokenUsageTermination(
+ component: Component<ComponentConfig>
+): component is Component<TokenUsageTerminationConfig> {
+ return isComponentOfType(component, PROVIDERS.TOKEN_USAGE);
+}
+
+export function isHandoffTermination(
+ component: Component<ComponentConfig>
+): component is Component<HandoffTerminationConfig> {
+ return isComponentOfType(component, PROVIDERS.HANDOFF);
+}
+
+export function isTimeoutTermination(
+ component: Component<ComponentConfig>
+): component is Component<TimeoutTerminationConfig> {
+ return isComponentOfType(component, PROVIDERS.TIMEOUT);
+}
+
+export function isExternalTermination(
+ component: Component<ComponentConfig>
+): component is Component<ExternalTerminationConfig> {
+ return isComponentOfType(component, PROVIDERS.EXTERNAL);
+}
+
+export function isSourceMatchTermination(
+ component: Component<ComponentConfig>
+): component is Component<SourceMatchTerminationConfig> {
+ return isComponentOfType(component, PROVIDERS.SOURCE_MATCH);
+}
+
+export function isTextMessageTermination(
+ component: Component<ComponentConfig>
+): component is Component<TextMessageTerminationConfig> {
+ return isComponentOfType(component, PROVIDERS.TEXT_MESSAGE);
+}
+
// Context provider guards with proper type narrowing
export function isUnboundedContext(
component: Component<ComponentConfig>
@@ -242,6 +372,13 @@ export function isUnboundedContext(
return isComponentOfType(component, PROVIDERS.UNBOUNDED_CONTEXT);
}
+// General category type guards
+export function isWorkbenchComponent(
+ component: Component<ComponentConfig>
+): component is Component<WorkbenchConfig> {
+ return component.component_type === "workbench";
+}
+
// Runtime assertions
export function assertComponentType<P extends Provider>(
component: Component<ComponentConfig>,
diff --git a/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx b/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx
index 91a88cdd3..2842301be 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/atoms.tsx
@@ -126,20 +126,17 @@ export const TruncatableText = memo(
{shouldTruncate && (
<div className="mt-2 flex items-center justify-end gap-2">
- <Tooltip title={isExpanded ? "Show less" : "Show more"}>
- <button
- type="button"
- onClick={toggleExpand}
- className="inline-flex items-center justify-center p-2 rounded bg-secondary text-primary hover:text-accent hover:scale-105 transition-all duration-300 z-10"
- aria-label={isExpanded ? "Show less" : "Show more"}
- >
- {isExpanded ? (
- <ChevronUp size={18} />
- ) : (
- <ChevronDown size={18} />
- )}
- </button>
- </Tooltip>
+ {/* <Tooltip title={isExpanded ? "Show less" : "Show more"}> */}
+ <button
+ title={isExpanded ? "Show less" : "Show more"}
+ type="button"
+ onClick={toggleExpand}
+ className="inline-flex items-center justify-center p-2 rounded bg-secondary text-primary hover:text-accent hover:scale-105 transition-all duration-300 z-10"
+ aria-label={isExpanded ? "Show less" : "Show more"}
+ >
+ {isExpanded ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
+ </button>
+ {/* </Tooltip> */}
{showFullscreen && (
<Tooltip title="Fullscreen">
diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/default_gallery.json b/python/packages/autogen-studio/frontend/src/components/views/gallery/default_gallery.json
index 08fc16f8f..ebbb5d21e 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/default_gallery.json
+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/default_gallery.json
@@ -4,8 +4,6 @@
"url": null,
"metadata": {
"author": "AutoGen Team",
- "created_at": "2025-02-21T20:43:06.400850",
- "updated_at": "2025-02-21T20:43:07.501068",
"version": "1.0.0",
"description": "A default gallery containing basic components for human-in-loop conversations",
"tags": ["human-in-loop", "assistant", "web agents"],
@@ -19,8 +17,8 @@
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
+ "version": 2,
+ "component_version": 2,
"description": "An agent that provides assistance with ability to use tools.",
"label": "AssistantAgent",
"config": {
@@ -32,28 +30,37 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
- "tools": [
+ "workbench": [
{
- "provider": "autogen_core.tools.FunctionTool",
- "component_type": "tool",
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
"version": 1,
"component_version": 1,
- "description": "Create custom tools by wrapping standard Python functions.",
- "label": "FunctionTool",
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution.",
+ "label": "StaticWorkbench",
"config": {
- "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
- "name": "calculator",
- "description": "A simple calculator that performs basic arithmetic operations",
- "global_imports": [],
- "has_cancellation_support": false
+ "tools": [
+ {
+ "provider": "autogen_core.tools.FunctionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "Create custom tools by wrapping standard Python functions.",
+ "label": "FunctionTool",
+ "config": {
+ "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
+ "name": "calculator",
+ "description": "A simple calculator that performs basic arithmetic operations",
+ "global_imports": [],
+ "has_cancellation_support": false
+ }
+ }
+ ]
}
}
],
- "handoffs": [],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -67,7 +74,8 @@
"system_message": "You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "metadata": {}
}
},
{
@@ -86,9 +94,7 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
"description": "an agent that solves tasks by browsing the web",
"headless": true,
@@ -102,8 +108,8 @@
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
+ "version": 2,
+ "component_version": 2,
"description": "an agent that verifies and summarizes information",
"label": "Verification Assistant",
"config": {
@@ -115,12 +121,19 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
- "tools": [],
- "handoffs": [],
+ "workbench": [
+ {
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
+ "version": 1,
+ "component_version": 1,
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution.",
+ "label": "StaticWorkbench",
+ "config": { "tools": [] }
+ }
+ ],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -134,7 +147,8 @@
"system_message": "You are a task verification assistant who is working with a web surfer agent to solve tasks. At each point, check if the task has been completed as requested by the user. If the websurfer_agent responds and the task has not yet been completed, respond with what is left to do and then say 'keep going'. If and only when the task has been completed, summarize and present a final answer that directly addresses the user task in detail and then respond with TERMINATE.",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "metadata": {}
}
},
{
@@ -158,9 +172,7 @@
"component_version": 1,
"description": "OpenAI GPT-4o-mini",
"label": "OpenAI GPT-4o Mini",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
{
"provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",
@@ -175,11 +187,25 @@
"vision": false,
"function_calling": true,
"json_output": false,
- "family": "unknown"
+ "family": "unknown",
+ "structured_output": false
},
"base_url": "http://localhost:1234/v1"
}
},
+ {
+ "provider": "autogen_ext.models.anthropic.AnthropicChatCompletionClient",
+ "component_type": "model",
+ "version": 1,
+ "component_version": 1,
+ "description": "Anthropic Claude-3 model client.",
+ "label": "Anthropic Claude-3-7",
+ "config": {
+ "model": "claude-3-7-sonnet-20250219",
+ "max_tokens": 4096,
+ "temperature": 1.0
+ }
+ },
{
"provider": "autogen_ext.models.openai.AzureOpenAIChatCompletionClient",
"component_type": "model",
@@ -189,7 +215,7 @@
"label": "AzureOpenAI GPT-4o-mini",
"config": {
"model": "gpt-4o-mini",
- "api_key": "sk-...",
+ "api_key": "**********",
"azure_endpoint": "https://{your-custom-endpoint}.openai.azure.com/",
"azure_deployment": "{your-azure-deployment}",
"api_version": "2024-06-01"
@@ -220,68 +246,17 @@
"description": "A tool that generates images based on a text description using OpenAI's DALL-E model. Note: Requires OpenAI API key to function.",
"label": "Image Generation Tool",
"config": {
- "source_code": "async def generate_image(\n query: str, output_dir: Optional[Path] = None, image_size: Literal[\"1024x1024\", \"512x512\", \"256x256\"] = \"1024x1024\"\n) -> List[str]:\n \"\"\"\n Generate images using OpenAI's DALL-E model based on a text description.\n\n Args:\n query: Natural language description of the desired image\n output_dir: Directory to save generated images (default: current directory)\n image_size: Size of generated image (1024x1024, 512x512, or 256x256)\n\n Returns:\n List[str]: Paths to the generated image files\n \"\"\"\n # Initialize the OpenAI client\n client = OpenAI()\n\n # Generate images using DALL-E 3\n response = client.images.generate(model=\"dall-e-3\", prompt=query, n=1, response_format=\"b64_json\", size=image_size)\n\n saved_files = []\n\n # Process the response\n if response.data:\n for image_data in response.data:\n # Generate a unique filename\n file_name = f\"{uuid.uuid4()}.png\"\n\n # Use output_dir if provided, otherwise use current directory\n file_path = Path(output_dir) / file_name if output_dir else Path(file_name)\n\n base64_str = image_data.b64_json\n img = Image.open(io.BytesIO(base64.decodebytes(bytes(base64_str, \"utf-8\"))))\n\n # Save the image to a file\n img.save(file_path)\n\n saved_files.append(str(file_path))\n\n return saved_files\n",
+ "source_code": "async def generate_image(\n query: str, output_dir: Optional[Path] = None, image_size: Literal[\"1024x1024\", \"512x512\", \"256x256\"] = \"1024x1024\"\n) -> List[str]:\n \"\"\"\n Generate images using OpenAI's DALL-E model based on a text description.\n\n Args:\n query: Natural language description of the desired image\n output_dir: Directory to save generated images (default: current directory)\n image_size: Size of generated image (1024x1024, 512x512, or 256x256)\n\n Returns:\n List[str]: Paths to the generated image files\n \"\"\"\n # Initialize the OpenAI client\n client = OpenAI()\n\n # Generate images using DALL-E 3\n response = client.images.generate(model=\"dall-e-3\", prompt=query, n=1, response_format=\"b64_json\", size=image_size)\n\n saved_files = []\n\n # Process the response\n if response.data:\n for image_data in response.data:\n # Generate a unique filename\n file_name: str = f\"{uuid.uuid4()}.png\"\n\n # Use output_dir if provided, otherwise use current directory\n file_path = Path(output_dir) / file_name if output_dir else Path(file_name)\n\n base64_str = image_data.b64_json\n if base64_str:\n img = Image.open(io.BytesIO(base64.decodebytes(bytes(base64_str, \"utf-8\"))))\n # Save the image to a file\n img.save(file_path)\n saved_files.append(str(file_path))\n\n return saved_files\n",
"name": "generate_image",
"description": "Generate images using DALL-E based on text descriptions.",
"global_imports": [
"io",
"uuid",
"base64",
- {
- "module": "typing",
- "imports": ["List", "Optional", "Literal"]
- },
- {
- "module": "pathlib",
- "imports": ["Path"]
- },
- {
- "module": "openai",
- "imports": ["OpenAI"]
- },
- {
- "module": "PIL",
- "imports": ["Image"]
- }
- ],
- "has_cancellation_support": false
- }
- },
- {
- "provider": "autogen_core.tools.FunctionTool",
- "component_type": "tool",
- "version": 1,
- "component_version": 1,
- "description": "A tool that generates a PDF file from a list of images.Requires the PyFPDF and pillow library to function.",
- "label": "PDF Generation Tool",
- "config": {
- "source_code": "async def generate_pdf(\n sections: List[Dict[str, Optional[str]]], output_file: str = \"report.pdf\", report_title: str = \"PDF Report\"\n) -> str:\n \"\"\"\n Generate a PDF report with formatted sections including text and images.\n\n Args:\n sections: List of dictionaries containing section details with keys:\n - title: Section title\n - level: Heading level (title, h1, h2)\n - content: Section text content\n - image: Optional image URL or file path\n output_file: Name of output PDF file\n report_title: Title shown at top of report\n\n Returns:\n str: Path to the generated PDF file\n \"\"\"\n\n def normalize_text(text: str) -> str:\n \"\"\"Normalize Unicode text to ASCII.\"\"\"\n return unicodedata.normalize(\"NFKD\", text).encode(\"ascii\", \"ignore\").decode(\"ascii\")\n\n def get_image(image_url_or_path):\n \"\"\"Fetch image from URL or local path.\"\"\"\n if image_url_or_path.startswith((\"http://\", \"https://\")):\n response = requests.get(image_url_or_path)\n if response.status_code == 200:\n return BytesIO(response.content)\n elif Path(image_url_or_path).is_file():\n return open(image_url_or_path, \"rb\")\n return None\n\n def add_rounded_corners(img, radius=6):\n \"\"\"Add rounded corners to an image.\"\"\"\n mask = Image.new(\"L\", img.size, 0)\n draw = ImageDraw.Draw(mask)\n draw.rounded_rectangle([(0, 0), img.size], radius, fill=255)\n img = ImageOps.fit(img, mask.size, centering=(0.5, 0.5))\n img.putalpha(mask)\n return img\n\n class PDF(FPDF):\n \"\"\"Custom PDF class with header and content formatting.\"\"\"\n\n def header(self):\n self.set_font(\"Arial\", \"B\", 12)\n normalized_title = normalize_text(report_title)\n self.cell(0, 10, normalized_title, 0, 1, \"C\")\n\n def chapter_title(self, txt):\n self.set_font(\"Arial\", \"B\", 12)\n normalized_txt = normalize_text(txt)\n self.cell(0, 10, normalized_txt, 0, 1, \"L\")\n self.ln(2)\n\n def chapter_body(self, body):\n self.set_font(\"Arial\", \"\", 12)\n normalized_body = normalize_text(body)\n self.multi_cell(0, 10, normalized_body)\n self.ln()\n\n def add_image(self, img_data):\n img = Image.open(img_data)\n img = add_rounded_corners(img)\n img_path = Path(f\"temp_{uuid.uuid4().hex}.png\")\n img.save(img_path, format=\"PNG\")\n self.image(str(img_path), x=None, y=None, w=190 if img.width > 190 else img.width)\n self.ln(10)\n img_path.unlink()\n\n # Initialize PDF\n pdf = PDF()\n pdf.add_page()\n font_size = {\"title\": 16, \"h1\": 14, \"h2\": 12, \"body\": 12}\n\n # Add sections\n for section in sections:\n title = section.get(\"title\", \"\")\n level = section.get(\"level\", \"h1\")\n content = section.get(\"content\", \"\")\n image = section.get(\"image\")\n\n pdf.set_font(\"Arial\", \"B\" if level in font_size else \"\", font_size.get(level, font_size[\"body\"]))\n pdf.chapter_title(title)\n\n if content:\n pdf.chapter_body(content)\n\n if image:\n img_data = get_image(image)\n if img_data:\n pdf.add_image(img_data)\n if isinstance(img_data, BytesIO):\n img_data.close()\n\n pdf.output(output_file)\n return output_file\n",
- "name": "generate_pdf",
- "description": "Generate PDF reports with formatted sections containing text and images",
- "global_imports": [
- "uuid",
- "requests",
- "unicodedata",
- {
- "module": "typing",
- "imports": ["List", "Dict", "Optional"]
- },
- {
- "module": "pathlib",
- "imports": ["Path"]
- },
- {
- "module": "fpdf",
- "imports": ["FPDF"]
- },
- {
- "module": "PIL",
- "imports": ["Image", "ImageDraw", "ImageOps"]
- },
- {
- "module": "io",
- "imports": ["BytesIO"]
- }
+ { "module": "typing", "imports": ["List", "Optional", "Literal"] },
+ { "module": "pathlib", "imports": ["Path"] },
+ { "module": "openai", "imports": ["OpenAI"] },
+ { "module": "PIL", "imports": ["Image"] }
],
"has_cancellation_support": false
}
@@ -300,23 +275,11 @@
"global_imports": [
"os",
"html2text",
- {
- "module": "typing",
- "imports": ["Optional", "Dict"]
- },
+ { "module": "typing", "imports": ["Optional", "Dict"] },
"httpx",
- {
- "module": "bs4",
- "imports": ["BeautifulSoup"]
- },
- {
- "module": "html2text",
- "imports": ["HTML2Text"]
- },
- {
- "module": "urllib.parse",
- "imports": ["urljoin"]
- }
+ { "module": "bs4", "imports": ["BeautifulSoup"] },
+ { "module": "html2text", "imports": ["HTML2Text"] },
+ { "module": "urllib.parse", "imports": ["urljoin"] }
],
"has_cancellation_support": false
}
@@ -329,26 +292,17 @@
"description": "A tool that performs Bing searches using the Bing Web Search API. Requires the requests library, BING_SEARCH_KEY env variable to function.",
"label": "Bing Search Tool",
"config": {
- "source_code": "async def bing_search(\n query: str,\n num_results: int = 3,\n include_snippets: bool = True,\n include_content: bool = True,\n content_max_length: Optional[int] = 10000,\n language: str = \"en\",\n country: Optional[str] = None,\n safe_search: str = \"moderate\",\n response_filter: str = \"webpages\",\n) -> List[Dict[str, str]]:\n \"\"\"\n Perform a Bing search using the Bing Web Search API.\n\n Args:\n query: Search query string\n num_results: Number of results to return (max 50)\n include_snippets: Include result snippets in output\n include_content: Include full webpage content in markdown format\n content_max_length: Maximum length of webpage content (if included)\n language: Language code for search results (e.g., 'en', 'es', 'fr')\n country: Optional market code for search results (e.g., 'us', 'uk')\n safe_search: SafeSearch setting ('off', 'moderate', or 'strict')\n response_filter: Type of results ('webpages', 'news', 'images', or 'videos')\n\n Returns:\n List[Dict[str, str]]: List of search results\n\n Raises:\n ValueError: If API credentials are invalid or request fails\n \"\"\"\n # Get and validate API key\n api_key = os.getenv(\"BING_SEARCH_KEY\", \"\").strip()\n\n if not api_key:\n raise ValueError(\n \"BING_SEARCH_KEY environment variable is not set. \" \"Please obtain an API key from Azure Portal.\"\n )\n\n # Validate safe_search parameter\n valid_safe_search = [\"off\", \"moderate\", \"strict\"]\n if safe_search.lower() not in valid_safe_search:\n raise ValueError(f\"Invalid safe_search value. Must be one of: {', '.join(valid_safe_search)}\")\n\n # Validate response_filter parameter\n valid_filters = [\"webpages\", \"news\", \"images\", \"videos\"]\n if response_filter.lower() not in valid_filters:\n raise ValueError(f\"Invalid response_filter value. Must be one of: {', '.join(valid_filters)}\")\n\n async def fetch_page_content(url: str, max_length: Optional[int] = 50000) -> str:\n \"\"\"Helper function to fetch and convert webpage content to markdown\"\"\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n h2t = html2text.HTML2Text()\n h2t.body_width = 0\n h2t.ignore_images = False\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n markdown = h2t.handle(str(soup))\n\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except Exception as e:\n return f\"Error fetching content: {str(e)}\"\n\n # Build request headers and parameters\n headers = {\"Ocp-Apim-Subscription-Key\": api_key, \"Accept\": \"application/json\"}\n\n params = {\n \"q\": query,\n \"count\": min(max(1, num_results), 50),\n \"mkt\": f\"{language}-{country.upper()}\" if country else language,\n \"safeSearch\": safe_search.capitalize(),\n \"responseFilter\": response_filter,\n \"textFormat\": \"raw\",\n }\n\n # Make the request\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(\n \"https://api.bing.microsoft.com/v7.0/search\", headers=headers, params=params, timeout=10\n )\n\n # Handle common error cases\n if response.status_code == 401:\n raise ValueError(\"Authentication failed. Please verify your Bing Search API key.\")\n elif response.status_code == 403:\n raise ValueError(\n \"Access forbidden. This could mean:\\n\"\n \"1. The API key is invalid\\n\"\n \"2. The API key has expired\\n\"\n \"3. You've exceeded your API quota\"\n )\n elif response.status_code == 429:\n raise ValueError(\"API quota exceeded. Please try again later.\")\n\n response.raise_for_status()\n data = response.json()\n\n # Process results based on response_filter\n results = []\n if response_filter == \"webpages\" and \"webPages\" in data:\n items = data[\"webPages\"][\"value\"]\n elif response_filter == \"news\" and \"news\" in data:\n items = data[\"news\"][\"value\"]\n elif response_filter == \"images\" and \"images\" in data:\n items = data[\"images\"][\"value\"]\n elif response_filter == \"videos\" and \"videos\" in data:\n items = data[\"videos\"][\"value\"]\n else:\n if not any(key in data for key in [\"webPages\", \"news\", \"images\", \"videos\"]):\n return [] # No results found\n raise ValueError(f\"No {response_filter} results found in API response\")\n\n # Extract relevant information based on result type\n for item in items:\n result = {\"title\": item.get(\"name\", \"\")}\n\n if response_filter == \"webpages\":\n result[\"link\"] = item.get(\"url\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"snippet\", \"\")\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n elif response_filter == \"news\":\n result[\"link\"] = item.get(\"url\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n result[\"date\"] = item.get(\"datePublished\", \"\")\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n elif response_filter == \"images\":\n result[\"link\"] = item.get(\"contentUrl\", \"\")\n result[\"thumbnail\"] = item.get(\"thumbnailUrl\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n\n elif response_filter == \"videos\":\n result[\"link\"] = item.get(\"contentUrl\", \"\")\n result[\"thumbnail\"] = item.get(\"thumbnailUrl\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n result[\"duration\"] = item.get(\"duration\", \"\")\n\n results.append(result)\n\n return results[:num_results]\n\n except httpx.RequestException as e:\n error_msg = str(e)\n if \"InvalidApiKey\" in error_msg:\n raise ValueError(\"Invalid API key. Please check your BING_SEARCH_KEY environment variable.\") from e\n elif \"KeyExpired\" in error_msg:\n raise ValueError(\"API key has expired. Please generate a new key.\") from e\n else:\n raise ValueError(f\"Search request failed: {error_msg}\") from e\n except json.JSONDecodeError:\n raise ValueError(\"Failed to parse API response. \" \"Please verify your API credentials and try again.\") from None\n except Exception as e:\n raise ValueError(f\"Unexpected error during search: {str(e)}\") from e\n",
+ "source_code": "async def bing_search(\n query: str,\n num_results: int = 3,\n include_snippets: bool = True,\n include_content: bool = True,\n content_max_length: Optional[int] = 10000,\n language: str = \"en\",\n country: Optional[str] = None,\n safe_search: str = \"moderate\",\n response_filter: str = \"webpages\",\n) -> List[Dict[str, str]]:\n \"\"\"\n Perform a Bing search using the Bing Web Search API.\n\n Args:\n query: Search query string\n num_results: Number of results to return (max 50)\n include_snippets: Include result snippets in output\n include_content: Include full webpage content in markdown format\n content_max_length: Maximum length of webpage content (if included)\n language: Language code for search results (e.g., 'en', 'es', 'fr')\n country: Optional market code for search results (e.g., 'us', 'uk')\n safe_search: SafeSearch setting ('off', 'moderate', or 'strict')\n response_filter: Type of results ('webpages', 'news', 'images', or 'videos')\n\n Returns:\n List[Dict[str, str]]: List of search results\n\n Raises:\n ValueError: If API credentials are invalid or request fails\n \"\"\"\n # Get and validate API key\n api_key = os.getenv(\"BING_SEARCH_KEY\", \"\").strip()\n\n if not api_key:\n raise ValueError(\n \"BING_SEARCH_KEY environment variable is not set. \" \"Please obtain an API key from Azure Portal.\"\n )\n\n # Validate safe_search parameter\n valid_safe_search = [\"off\", \"moderate\", \"strict\"]\n if safe_search.lower() not in valid_safe_search:\n raise ValueError(f\"Invalid safe_search value. Must be one of: {', '.join(valid_safe_search)}\")\n\n # Validate response_filter parameter\n valid_filters = [\"webpages\", \"news\", \"images\", \"videos\"]\n if response_filter.lower() not in valid_filters:\n raise ValueError(f\"Invalid response_filter value. Must be one of: {', '.join(valid_filters)}\")\n\n async def fetch_page_content(url: str, max_length: Optional[int] = 50000) -> str:\n \"\"\"Helper function to fetch and convert webpage content to markdown\"\"\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n h2t = html2text.HTML2Text()\n h2t.body_width = 0\n h2t.ignore_images = False\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n markdown = h2t.handle(str(soup))\n\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except Exception as e:\n return f\"Error fetching content: {str(e)}\"\n\n # Build request headers and parameters\n headers = {\"Ocp-Apim-Subscription-Key\": api_key, \"Accept\": \"application/json\"}\n\n params = {\n \"q\": query,\n \"count\": min(max(1, num_results), 50),\n \"mkt\": f\"{language}-{country.upper()}\" if country else language,\n \"safeSearch\": safe_search.capitalize(),\n \"responseFilter\": response_filter,\n \"textFormat\": \"raw\",\n }\n\n # Make the request\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(\n \"https://api.bing.microsoft.com/v7.0/search\", headers=headers, params=params, timeout=10\n )\n\n # Handle common error cases\n if response.status_code == 401:\n raise ValueError(\"Authentication failed. Please verify your Bing Search API key.\")\n elif response.status_code == 403:\n raise ValueError(\n \"Access forbidden. This could mean:\\n\"\n \"1. The API key is invalid\\n\"\n \"2. The API key has expired\\n\"\n \"3. You've exceeded your API quota\"\n )\n elif response.status_code == 429:\n raise ValueError(\"API quota exceeded. Please try again later.\")\n\n response.raise_for_status()\n data = response.json()\n\n # Process results based on response_filter\n results = []\n if response_filter == \"webpages\" and \"webPages\" in data:\n items = data[\"webPages\"][\"value\"]\n elif response_filter == \"news\" and \"news\" in data:\n items = data[\"news\"][\"value\"]\n elif response_filter == \"images\" and \"images\" in data:\n items = data[\"images\"][\"value\"]\n elif response_filter == \"videos\" and \"videos\" in data:\n items = data[\"videos\"][\"value\"]\n else:\n if not any(key in data for key in [\"webPages\", \"news\", \"images\", \"videos\"]):\n return [] # No results found\n raise ValueError(f\"No {response_filter} results found in API response\")\n\n # Extract relevant information based on result type\n for item in items:\n result = {\"title\": item.get(\"name\", \"\")}\n\n if response_filter == \"webpages\":\n result[\"link\"] = item.get(\"url\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"snippet\", \"\")\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n elif response_filter == \"news\":\n result[\"link\"] = item.get(\"url\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n result[\"date\"] = item.get(\"datePublished\", \"\")\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n elif response_filter == \"images\":\n result[\"link\"] = item.get(\"contentUrl\", \"\")\n result[\"thumbnail\"] = item.get(\"thumbnailUrl\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n\n elif response_filter == \"videos\":\n result[\"link\"] = item.get(\"contentUrl\", \"\")\n result[\"thumbnail\"] = item.get(\"thumbnailUrl\", \"\")\n if include_snippets:\n result[\"snippet\"] = item.get(\"description\", \"\")\n result[\"duration\"] = item.get(\"duration\", \"\")\n\n results.append(result)\n\n return results[:num_results]\n\n except httpx.HTTPError as e:\n error_msg = str(e)\n if \"InvalidApiKey\" in error_msg:\n raise ValueError(\"Invalid API key. Please check your BING_SEARCH_KEY environment variable.\") from e\n elif \"KeyExpired\" in error_msg:\n raise ValueError(\"API key has expired. Please generate a new key.\") from e\n else:\n raise ValueError(f\"Search request failed: {error_msg}\") from e\n except json.JSONDecodeError:\n raise ValueError(\"Failed to parse API response. \" \"Please verify your API credentials and try again.\") from None\n except Exception as e:\n raise ValueError(f\"Unexpected error during search: {str(e)}\") from e\n",
"name": "bing_search",
"description": "\n Perform Bing searches using the Bing Web Search API. Requires BING_SEARCH_KEY environment variable.\n Supports web, news, image, and video searches.\n See function documentation for detailed setup instructions.\n ",
"global_imports": [
- {
- "module": "typing",
- "imports": ["List", "Dict", "Optional"]
- },
+ { "module": "typing", "imports": ["List", "Dict", "Optional"] },
"os",
"httpx",
"json",
"html2text",
- {
- "module": "bs4",
- "imports": ["BeautifulSoup"]
- },
- {
- "module": "urllib.parse",
- "imports": ["urljoin"]
- }
+ { "module": "bs4", "imports": ["BeautifulSoup"] },
+ { "module": "urllib.parse", "imports": ["urljoin"] }
],
"has_cancellation_support": false
}
@@ -365,24 +319,40 @@
"name": "google_search",
"description": "\n Perform Google searches using the Custom Search API with optional webpage content fetching.\n Requires GOOGLE_API_KEY and GOOGLE_CSE_ID environment variables to be set.\n ",
"global_imports": [
- {
- "module": "typing",
- "imports": ["List", "Dict", "Optional"]
- },
+ { "module": "typing", "imports": ["List", "Dict", "Optional"] },
"os",
"httpx",
"html2text",
- {
- "module": "bs4",
- "imports": ["BeautifulSoup"]
- },
- {
- "module": "urllib.parse",
- "imports": ["urljoin"]
- }
+ { "module": "bs4", "imports": ["BeautifulSoup"] },
+ { "module": "urllib.parse", "imports": ["urljoin"] }
],
"has_cancellation_support": false
}
+ },
+ {
+ "provider": "autogen_ext.tools.code_execution.PythonCodeExecutionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "A tool that executes Python code in a local environment.",
+ "label": "Python Code Execution Tool",
+ "config": {
+ "executor": {
+ "provider": "autogen_ext.code_executors.local.LocalCommandLineCodeExecutor",
+ "component_type": "code_executor",
+ "version": 1,
+ "component_version": 1,
+ "description": "A code executor class that executes code through a local command line\n environment.",
+ "label": "LocalCommandLineCodeExecutor",
+ "config": {
+ "timeout": 360,
+ "work_dir": ".coding",
+ "functions_module": "functions",
+ "cleanup_temp_files": true
+ }
+ },
+ "description": "Execute Python code blocks."
+ }
}
],
"terminations": [
@@ -393,9 +363,7 @@
"component_version": 1,
"description": "Terminate the conversation if a specific text is mentioned.",
"label": "TextMentionTermination",
- "config": {
- "text": "TERMINATE"
- }
+ "config": { "text": "TERMINATE" }
},
{
"provider": "autogen_agentchat.conditions.MaxMessageTermination",
@@ -404,10 +372,7 @@
"component_version": 1,
"description": "Terminate the conversation after a maximum number of messages have been exchanged.",
"label": "MaxMessageTermination",
- "config": {
- "max_messages": 10,
- "include_agent_event": false
- }
+ "config": { "max_messages": 10, "include_agent_event": false }
},
{
"provider": "autogen_agentchat.base.OrTerminationCondition",
@@ -425,9 +390,7 @@
"component_version": 1,
"description": "Terminate the conversation if a specific text is mentioned.",
"label": "TextMentionTermination",
- "config": {
- "text": "TERMINATE"
- }
+ "config": { "text": "TERMINATE" }
},
{
"provider": "autogen_agentchat.conditions.MaxMessageTermination",
@@ -436,10 +399,7 @@
"component_version": 1,
"description": "Terminate the conversation after a maximum number of messages have been exchanged.",
"label": "MaxMessageTermination",
- "config": {
- "max_messages": 10,
- "include_agent_event": false
- }
+ "config": { "max_messages": 10, "include_agent_event": false }
}
]
}
@@ -458,8 +418,8 @@
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
+ "version": 2,
+ "component_version": 2,
"description": "An agent that provides assistance with tool use.",
"label": "AssistantAgent",
"config": {
@@ -471,28 +431,37 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
- "tools": [
+ "workbench": [
{
- "provider": "autogen_core.tools.FunctionTool",
- "component_type": "tool",
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
"version": 1,
"component_version": 1,
- "description": "Create custom tools by wrapping standard Python functions.",
- "label": "FunctionTool",
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution.",
+ "label": "StaticWorkbench",
"config": {
- "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
- "name": "calculator",
- "description": "A simple calculator that performs basic arithmetic operations",
- "global_imports": [],
- "has_cancellation_support": false
+ "tools": [
+ {
+ "provider": "autogen_core.tools.FunctionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "Create custom tools by wrapping standard Python functions.",
+ "label": "FunctionTool",
+ "config": {
+ "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
+ "name": "calculator",
+ "description": "A simple calculator that performs basic arithmetic operations",
+ "global_imports": [],
+ "has_cancellation_support": false
+ }
+ }
+ ]
}
}
],
- "handoffs": [],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -506,7 +475,8 @@
"system_message": "You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "metadata": {}
}
}
],
@@ -525,9 +495,7 @@
"component_version": 1,
"description": "Terminate the conversation if a specific text is mentioned.",
"label": "TextMentionTermination",
- "config": {
- "text": "TERMINATE"
- }
+ "config": { "text": "TERMINATE" }
},
{
"provider": "autogen_agentchat.conditions.MaxMessageTermination",
@@ -536,14 +504,12 @@
"component_version": 1,
"description": "Terminate the conversation after a maximum number of messages have been exchanged.",
"label": "MaxMessageTermination",
- "config": {
- "max_messages": 10,
- "include_agent_event": false
- }
+ "config": { "max_messages": 10, "include_agent_event": false }
}
]
}
- }
+ },
+ "emit_team_events": false
}
},
{
@@ -558,8 +524,8 @@
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
+ "version": 2,
+ "component_version": 2,
"description": "An agent that provides assistance with tool use.",
"label": "AssistantAgent",
"config": {
@@ -571,28 +537,37 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
- "tools": [
+ "workbench": [
{
- "provider": "autogen_core.tools.FunctionTool",
- "component_type": "tool",
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
"version": 1,
"component_version": 1,
- "description": "Create custom tools by wrapping standard Python functions.",
- "label": "FunctionTool",
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution.",
+ "label": "StaticWorkbench",
"config": {
- "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
- "name": "calculator",
- "description": "A simple calculator that performs basic arithmetic operations",
- "global_imports": [],
- "has_cancellation_support": false
+ "tools": [
+ {
+ "provider": "autogen_core.tools.FunctionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "Create custom tools by wrapping standard Python functions.",
+ "label": "FunctionTool",
+ "config": {
+ "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
+ "name": "calculator",
+ "description": "A simple calculator that performs basic arithmetic operations",
+ "global_imports": [],
+ "has_cancellation_support": false
+ }
+ }
+ ]
}
}
],
- "handoffs": [],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -606,14 +581,15 @@
"system_message": "You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "metadata": {}
}
},
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
+ "version": 2,
+ "component_version": 2,
"description": "An agent that provides assistance with tool use.",
"label": "AssistantAgent",
"config": {
@@ -625,12 +601,19 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
- "tools": [],
- "handoffs": [],
+ "workbench": [
+ {
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
+ "version": 1,
+ "component_version": 1,
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution.",
+ "label": "StaticWorkbench",
+ "config": { "tools": [] }
+ }
+ ],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -644,7 +627,8 @@
"system_message": "You are a helpful assistant. Critique the assistant's output and suggest improvements.",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "metadata": {}
}
}
],
@@ -655,9 +639,7 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
"termination_condition": {
"provider": "autogen_agentchat.base.OrTerminationCondition",
@@ -674,9 +656,7 @@
"component_version": 1,
"description": "Terminate the conversation if a specific text is mentioned.",
"label": "TextMentionTermination",
- "config": {
- "text": "TERMINATE"
- }
+ "config": { "text": "TERMINATE" }
},
{
"provider": "autogen_agentchat.conditions.MaxMessageTermination",
@@ -685,17 +665,16 @@
"component_version": 1,
"description": "Terminate the conversation after a maximum number of messages have been exchanged.",
"label": "MaxMessageTermination",
- "config": {
- "max_messages": 10,
- "include_agent_event": false
- }
+ "config": { "max_messages": 10, "include_agent_event": false }
}
]
}
},
"selector_prompt": "You are in a role play game. The following roles are available:\n{roles}.\nRead the following conversation. Then select the next role from {participants} to play. Only return the role.\n\n{history}\n\nRead the above conversation. Then select the next role from {participants} to play. Only return the role.\n",
"allow_repeated_speaker": false,
- "max_selector_attempts": 3
+ "max_selector_attempts": 3,
+ "emit_team_events": false,
+ "model_client_streaming": false
}
},
{
@@ -723,9 +702,7 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
"description": "an agent that solves tasks by browsing the web",
"headless": true,
@@ -739,8 +716,8 @@
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
+ "version": 2,
+ "component_version": 2,
"description": "An agent that provides assistance with tool use.",
"label": "AssistantAgent",
"config": {
@@ -752,12 +729,19 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
- "tools": [],
- "handoffs": [],
+ "workbench": [
+ {
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
+ "version": 1,
+ "component_version": 1,
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution.",
+ "label": "StaticWorkbench",
+ "config": { "tools": [] }
+ }
+ ],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -771,7 +755,8 @@
"system_message": "You are a task verification assistant who is working with a web surfer agent to solve tasks. At each point, check if the task has been completed as requested by the user. If the websurfer_agent responds and the task has not yet been completed, respond with what is left to do and then say 'keep going'. If and only when the task has been completed, summarize and present a final answer that directly addresses the user task in detail and then respond with TERMINATE.",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "metadata": {}
}
},
{
@@ -794,9 +779,7 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "model": "gpt-4o-mini"
- }
+ "config": { "model": "gpt-4o-mini" }
},
"termination_condition": {
"provider": "autogen_agentchat.base.OrTerminationCondition",
@@ -813,10 +796,7 @@
"component_version": 1,
"description": "Terminate the conversation after a maximum number of messages have been exchanged.",
"label": "MaxMessageTermination",
- "config": {
- "max_messages": 20,
- "include_agent_event": false
- }
+ "config": { "max_messages": 20, "include_agent_event": false }
},
{
"provider": "autogen_agentchat.conditions.TextMentionTermination",
@@ -825,16 +805,16 @@
"component_version": 1,
"description": "Terminate the conversation if a specific text is mentioned.",
"label": "TextMentionTermination",
- "config": {
- "text": "TERMINATE"
- }
+ "config": { "text": "TERMINATE" }
}
]
}
},
"selector_prompt": "You are the cordinator of role play game. The following roles are available:\n{roles}. Given a task, the websurfer_agent will be tasked to address it by browsing the web and providing information. The assistant_agent will be tasked with verifying the information provided by the websurfer_agent and summarizing the information to present a final answer to the user. If the task needs assistance from a human user (e.g., providing feedback, preferences, or the task is stalled), you should select the user_proxy role to provide the necessary information.\n\nRead the following conversation. Then select the next role from {participants} to play. Only return the role.\n\n{history}\n\nRead the above conversation. Then select the next role from {participants} to play. Only return the role.",
"allow_repeated_speaker": false,
- "max_selector_attempts": 3
+ "max_selector_attempts": 3,
+ "emit_team_events": false,
+ "model_client_streaming": false
}
},
{
@@ -849,8 +829,8 @@
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
+ "version": 2,
+ "component_version": 2,
"description": "An agent that provides assistance with tool use.",
"label": "AssistantAgent",
"config": {
@@ -862,80 +842,82 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "temperature": 0.7,
- "model": "gpt-4o"
- }
+ "config": { "temperature": 0.7, "model": "gpt-4o" }
},
- "tools": [
+ "workbench": [
{
- "provider": "autogen_core.tools.FunctionTool",
- "component_type": "tool",
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
"version": 1,
"component_version": 1,
- "description": "Create custom tools by wrapping standard Python functions.",
- "label": "FunctionTool",
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution.",
+ "label": "StaticWorkbench",
"config": {
- "source_code": "async def google_search(\n query: str,\n num_results: int = 3,\n include_snippets: bool = True,\n include_content: bool = True,\n content_max_length: Optional[int] = 10000,\n language: str = \"en\",\n country: Optional[str] = None,\n safe_search: bool = True,\n) -> List[Dict[str, str]]:\n \"\"\"\n Perform a Google search using the Custom Search API and optionally fetch webpage content.\n\n Args:\n query: Search query string\n num_results: Number of results to return (max 10)\n include_snippets: Include result snippets in output\n include_content: Include full webpage content in markdown format\n content_max_length: Maximum length of webpage content (if included)\n language: Language code for search results (e.g., en, es, fr)\n country: Optional country code for search results (e.g., us, uk)\n safe_search: Enable safe search filtering\n\n Returns:\n List[Dict[str, str]]: List of search results, each containing:\n - title: Result title\n - link: Result URL\n - snippet: Result description (if include_snippets=True)\n - content: Webpage content in markdown (if include_content=True)\n \"\"\"\n api_key = os.getenv(\"GOOGLE_API_KEY\")\n cse_id = os.getenv(\"GOOGLE_CSE_ID\")\n\n if not api_key or not cse_id:\n raise ValueError(\"Missing required environment variables. Please set GOOGLE_API_KEY and GOOGLE_CSE_ID.\")\n\n num_results = min(max(1, num_results), 10)\n\n async def fetch_page_content(url: str, max_length: Optional[int] = 50000) -> str:\n \"\"\"Helper function to fetch and convert webpage content to markdown\"\"\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n h2t = html2text.HTML2Text()\n h2t.body_width = 0\n h2t.ignore_images = False\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n markdown = h2t.handle(str(soup))\n\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except Exception as e:\n return f\"Error fetching content: {str(e)}\"\n\n params = {\n \"key\": api_key,\n \"cx\": cse_id,\n \"q\": query,\n \"num\": num_results,\n \"hl\": language,\n \"safe\": \"active\" if safe_search else \"off\",\n }\n\n if country:\n params[\"gl\"] = country\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(\"https://www.googleapis.com/customsearch/v1\", params=params, timeout=10)\n response.raise_for_status()\n data = response.json()\n\n results = []\n if \"items\" in data:\n for item in data[\"items\"]:\n result = {\"title\": item.get(\"title\", \"\"), \"link\": item.get(\"link\", \"\")}\n if include_snippets:\n result[\"snippet\"] = item.get(\"snippet\", \"\")\n\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n results.append(result)\n\n return results\n\n except httpx.RequestError as e:\n raise ValueError(f\"Failed to perform search: {str(e)}\") from e\n except KeyError as e:\n raise ValueError(f\"Invalid API response format: {str(e)}\") from e\n except Exception as e:\n raise ValueError(f\"Error during search: {str(e)}\") from e\n",
- "name": "google_search",
- "description": "\n Perform Google searches using the Custom Search API with optional webpage content fetching.\n Requires GOOGLE_API_KEY and GOOGLE_CSE_ID environment variables to be set.\n ",
- "global_imports": [
- {
- "module": "typing",
- "imports": ["List", "Dict", "Optional"]
- },
- "os",
- "httpx",
- "html2text",
+ "tools": [
{
- "module": "bs4",
- "imports": ["BeautifulSoup"]
+ "provider": "autogen_core.tools.FunctionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "Create custom tools by wrapping standard Python functions.",
+ "label": "FunctionTool",
+ "config": {
+ "source_code": "async def google_search(\n query: str,\n num_results: int = 3,\n include_snippets: bool = True,\n include_content: bool = True,\n content_max_length: Optional[int] = 10000,\n language: str = \"en\",\n country: Optional[str] = None,\n safe_search: bool = True,\n) -> List[Dict[str, str]]:\n \"\"\"\n Perform a Google search using the Custom Search API and optionally fetch webpage content.\n\n Args:\n query: Search query string\n num_results: Number of results to return (max 10)\n include_snippets: Include result snippets in output\n include_content: Include full webpage content in markdown format\n content_max_length: Maximum length of webpage content (if included)\n language: Language code for search results (e.g., en, es, fr)\n country: Optional country code for search results (e.g., us, uk)\n safe_search: Enable safe search filtering\n\n Returns:\n List[Dict[str, str]]: List of search results, each containing:\n - title: Result title\n - link: Result URL\n - snippet: Result description (if include_snippets=True)\n - content: Webpage content in markdown (if include_content=True)\n \"\"\"\n api_key = os.getenv(\"GOOGLE_API_KEY\")\n cse_id = os.getenv(\"GOOGLE_CSE_ID\")\n\n if not api_key or not cse_id:\n raise ValueError(\"Missing required environment variables. Please set GOOGLE_API_KEY and GOOGLE_CSE_ID.\")\n\n num_results = min(max(1, num_results), 10)\n\n async def fetch_page_content(url: str, max_length: Optional[int] = 50000) -> str:\n \"\"\"Helper function to fetch and convert webpage content to markdown\"\"\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n h2t = html2text.HTML2Text()\n h2t.body_width = 0\n h2t.ignore_images = False\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n markdown = h2t.handle(str(soup))\n\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except Exception as e:\n return f\"Error fetching content: {str(e)}\"\n\n params = {\n \"key\": api_key,\n \"cx\": cse_id,\n \"q\": query,\n \"num\": num_results,\n \"hl\": language,\n \"safe\": \"active\" if safe_search else \"off\",\n }\n\n if country:\n params[\"gl\"] = country\n\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(\"https://www.googleapis.com/customsearch/v1\", params=params, timeout=10)\n response.raise_for_status()\n data = response.json()\n\n results = []\n if \"items\" in data:\n for item in data[\"items\"]:\n result = {\"title\": item.get(\"title\", \"\"), \"link\": item.get(\"link\", \"\")}\n if include_snippets:\n result[\"snippet\"] = item.get(\"snippet\", \"\")\n\n if include_content:\n result[\"content\"] = await fetch_page_content(result[\"link\"], max_length=content_max_length)\n\n results.append(result)\n\n return results\n\n except httpx.RequestError as e:\n raise ValueError(f\"Failed to perform search: {str(e)}\") from e\n except KeyError as e:\n raise ValueError(f\"Invalid API response format: {str(e)}\") from e\n except Exception as e:\n raise ValueError(f\"Error during search: {str(e)}\") from e\n",
+ "name": "google_search",
+ "description": "\n Perform Google searches using the Custom Search API with optional webpage content fetching.\n Requires GOOGLE_API_KEY and GOOGLE_CSE_ID environment variables to be set.\n ",
+ "global_imports": [
+ {
+ "module": "typing",
+ "imports": ["List", "Dict", "Optional"]
+ },
+ "os",
+ "httpx",
+ "html2text",
+ { "module": "bs4", "imports": ["BeautifulSoup"] },
+ {
+ "module": "urllib.parse",
+ "imports": ["urljoin"]
+ }
+ ],
+ "has_cancellation_support": false
+ }
},
{
- "module": "urllib.parse",
- "imports": ["urljoin"]
+ "provider": "autogen_core.tools.FunctionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "Create custom tools by wrapping standard Python functions.",
+ "label": "FunctionTool",
+ "config": {
+ "source_code": "async def fetch_webpage(\n url: str, include_images: bool = True, max_length: Optional[int] = None, headers: Optional[Dict[str, str]] = None\n) -> str:\n \"\"\"Fetch a webpage and convert it to markdown format.\n\n Args:\n url: The URL of the webpage to fetch\n include_images: Whether to include image references in the markdown\n max_length: Maximum length of the output markdown (if None, no limit)\n headers: Optional HTTP headers for the request\n\n Returns:\n str: Markdown version of the webpage content\n\n Raises:\n ValueError: If the URL is invalid or the page can't be fetched\n \"\"\"\n # Use default headers if none provided\n if headers is None:\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n # Fetch the webpage\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n # Parse HTML\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n # Configure HTML to Markdown converter\n h2t = html2text.HTML2Text()\n h2t.body_width = 0 # No line wrapping\n h2t.ignore_images = not include_images\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n # Convert to markdown\n markdown = h2t.handle(str(soup))\n\n # Trim if max_length is specified\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except httpx.RequestError as e:\n raise ValueError(f\"Failed to fetch webpage: {str(e)}\") from e\n except Exception as e:\n raise ValueError(f\"Error processing webpage: {str(e)}\") from e\n",
+ "name": "fetch_webpage",
+ "description": "Fetch a webpage and convert it to markdown format, with options for including images and limiting length",
+ "global_imports": [
+ "os",
+ "html2text",
+ {
+ "module": "typing",
+ "imports": ["Optional", "Dict"]
+ },
+ "httpx",
+ { "module": "bs4", "imports": ["BeautifulSoup"] },
+ {
+ "module": "html2text",
+ "imports": ["HTML2Text"]
+ },
+ {
+ "module": "urllib.parse",
+ "imports": ["urljoin"]
+ }
+ ],
+ "has_cancellation_support": false
+ }
}
- ],
- "has_cancellation_support": false
- }
- },
- {
- "provider": "autogen_core.tools.FunctionTool",
- "component_type": "tool",
- "version": 1,
- "component_version": 1,
- "description": "Create custom tools by wrapping standard Python functions.",
- "label": "FunctionTool",
- "config": {
- "source_code": "async def fetch_webpage(\n url: str, include_images: bool = True, max_length: Optional[int] = None, headers: Optional[Dict[str, str]] = None\n) -> str:\n \"\"\"Fetch a webpage and convert it to markdown format.\n\n Args:\n url: The URL of the webpage to fetch\n include_images: Whether to include image references in the markdown\n max_length: Maximum length of the output markdown (if None, no limit)\n headers: Optional HTTP headers for the request\n\n Returns:\n str: Markdown version of the webpage content\n\n Raises:\n ValueError: If the URL is invalid or the page can't be fetched\n \"\"\"\n # Use default headers if none provided\n if headers is None:\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n # Fetch the webpage\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n # Parse HTML\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n # Configure HTML to Markdown converter\n h2t = html2text.HTML2Text()\n h2t.body_width = 0 # No line wrapping\n h2t.ignore_images = not include_images\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n # Convert to markdown\n markdown = h2t.handle(str(soup))\n\n # Trim if max_length is specified\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except httpx.RequestError as e:\n raise ValueError(f\"Failed to fetch webpage: {str(e)}\") from e\n except Exception as e:\n raise ValueError(f\"Error processing webpage: {str(e)}\") from e\n",
- "name": "fetch_webpage",
- "description": "Fetch a webpage and convert it to markdown format, with options for including images and limiting length",
- "global_imports": [
- "os",
- "html2text",
- {
- "module": "typing",
- "imports": ["Optional", "Dict"]
- },
- "httpx",
- {
- "module": "bs4",
- "imports": ["BeautifulSoup"]
- },
- {
- "module": "html2text",
- "imports": ["HTML2Text"]
- },
- {
- "module": "urllib.parse",
- "imports": ["urljoin"]
- }
- ],
- "has_cancellation_support": false
+ ]
}
}
],
- "handoffs": [],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -949,14 +931,15 @@
"system_message": "You are a research assistant focused on finding accurate information.\n Use the google_search tool to find relevant information.\n Break down complex queries into specific search terms.\n Always verify information across multiple sources when possible.\n When you find relevant information, explain why it's relevant and how it connects to the query. When you get feedback from the a verifier agent, use your tools to act on the feedback and make progress.",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "metadata": {}
}
},
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
+ "version": 2,
+ "component_version": 2,
"description": "An agent that provides assistance with tool use.",
"label": "AssistantAgent",
"config": {
@@ -968,13 +951,19 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "temperature": 0.7,
- "model": "gpt-4o"
- }
+ "config": { "temperature": 0.7, "model": "gpt-4o" }
},
- "tools": [],
- "handoffs": [],
+ "workbench": [
+ {
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
+ "version": 1,
+ "component_version": 1,
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution.",
+ "label": "StaticWorkbench",
+ "config": { "tools": [] }
+ }
+ ],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -988,14 +977,15 @@
"system_message": "You are a research verification specialist.\n Your role is to:\n 1. Verify that search queries are effective and suggest improvements if needed\n 2. Explore drill downs where needed e.g, if the answer is likely in a link in the returned search results, suggest clicking on the link\n 3. Suggest additional angles or perspectives to explore. Be judicious in suggesting new paths to avoid scope creep or wasting resources, if the task appears to be addressed and we can provide a report, do this and respond with \"TERMINATE\".\n 4. Track progress toward answering the original question\n 5. When the research is complete, provide a detailed summary in markdown format. For incomplete research, end your message with \"CONTINUE RESEARCH\". For complete research, end your message with APPROVED.\n Your responses should be structured as:\n - Progress Assessment\n - Gaps/Issues (if any)\n - Suggestions (if needed)\n - Next Steps or Final Summary",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "metadata": {}
}
},
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
+ "version": 2,
+ "component_version": 2,
"description": "An agent that provides assistance with tool use.",
"label": "AssistantAgent",
"config": {
@@ -1007,13 +997,19 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "temperature": 0.7,
- "model": "gpt-4o"
- }
+ "config": { "temperature": 0.7, "model": "gpt-4o" }
},
- "tools": [],
- "handoffs": [],
+ "workbench": [
+ {
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
+ "version": 1,
+ "component_version": 1,
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution.",
+ "label": "StaticWorkbench",
+ "config": { "tools": [] }
+ }
+ ],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -1027,7 +1023,8 @@
"system_message": "You are a summary agent. Your role is to provide a detailed markdown summary of the research as a report to the user. Your report should have a reasonable title that matches the research question and should summarize the key details in the results found in natural an actionable manner. The main results/answer should be in the first paragraph. Where reasonable, your report should have clear comparison tables that drive critical insights. Most importantly, you should have a reference section and cite the key sources (where available) for facts obtained INSIDE THE MAIN REPORT. Also, where appropriate, you may add images if available that illustrate concepts needed for the summary.\n Your report should end with the word \"TERMINATE\" to signal the end of the conversation.",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "metadata": {}
}
}
],
@@ -1038,10 +1035,7 @@
"component_version": 1,
"description": "Chat completion client for OpenAI hosted models.",
"label": "OpenAIChatCompletionClient",
- "config": {
- "temperature": 0.7,
- "model": "gpt-4o"
- }
+ "config": { "temperature": 0.7, "model": "gpt-4o" }
},
"termination_condition": {
"provider": "autogen_agentchat.base.OrTerminationCondition",
@@ -1058,9 +1052,7 @@
"component_version": 1,
"description": "Terminate the conversation if a specific text is mentioned.",
"label": "TextMentionTermination",
- "config": {
- "text": "TERMINATE"
- }
+ "config": { "text": "TERMINATE" }
},
{
"provider": "autogen_agentchat.conditions.MaxMessageTermination",
@@ -1069,17 +1061,107 @@
"component_version": 1,
"description": "Terminate the conversation after a maximum number of messages have been exchanged.",
"label": "MaxMessageTermination",
- "config": {
- "max_messages": 30,
- "include_agent_event": false
- }
+ "config": { "max_messages": 30, "include_agent_event": false }
}
]
}
},
"selector_prompt": "You are coordinating a research team by selecting the team member to speak/act next. The following team member roles are available:\n {roles}.\n The research_assistant performs searches and analyzes information.\n The verifier evaluates progress and ensures completeness.\n The summary_agent provides a detailed markdown summary of the research as a report to the user.\n\n Given the current context, select the most appropriate next speaker.\n The research_assistant should search and analyze.\n The verifier should evaluate progress and guide the research (select this role is there is a need to verify/evaluate progress). You should ONLY select the summary_agent role if the research is complete and it is time to generate a report.\n\n Base your selection on:\n 1. Current stage of research\n 2. Last speaker's findings or suggestions\n 3. Need for verification vs need for new information\n Read the following conversation. Then select the next role from {participants} to play. Only return the role.\n\n {history}\n\n Read the above conversation. Then select the next role from {participants} to play. ONLY RETURN THE ROLE.",
"allow_repeated_speaker": true,
- "max_selector_attempts": 3
+ "max_selector_attempts": 3,
+ "emit_team_events": false,
+ "model_client_streaming": false
+ }
+ }
+ ],
+ "workbenches": [
+ {
+ "provider": "autogen_core.tools.StaticWorkbench",
+ "component_type": "workbench",
+ "version": 1,
+ "component_version": 1,
+ "description": "A static workbench containing basic tools like calculator and webpage fetcher for common tasks.",
+ "label": "Basic Tools Workbench",
+ "config": {
+ "tools": [
+ {
+ "provider": "autogen_core.tools.FunctionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "Create custom tools by wrapping standard Python functions.",
+ "label": "FunctionTool",
+ "config": {
+ "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
+ "name": "calculator",
+ "description": "A simple calculator that performs basic arithmetic operations",
+ "global_imports": [],
+ "has_cancellation_support": false
+ }
+ },
+ {
+ "provider": "autogen_core.tools.FunctionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "Create custom tools by wrapping standard Python functions.",
+ "label": "FunctionTool",
+ "config": {
+ "source_code": "async def fetch_webpage(\n url: str, include_images: bool = True, max_length: Optional[int] = None, headers: Optional[Dict[str, str]] = None\n) -> str:\n \"\"\"Fetch a webpage and convert it to markdown format.\n\n Args:\n url: The URL of the webpage to fetch\n include_images: Whether to include image references in the markdown\n max_length: Maximum length of the output markdown (if None, no limit)\n headers: Optional HTTP headers for the request\n\n Returns:\n str: Markdown version of the webpage content\n\n Raises:\n ValueError: If the URL is invalid or the page can't be fetched\n \"\"\"\n # Use default headers if none provided\n if headers is None:\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n\n try:\n # Fetch the webpage\n async with httpx.AsyncClient() as client:\n response = await client.get(url, headers=headers, timeout=10)\n response.raise_for_status()\n\n # Parse HTML\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # Remove script and style elements\n for script in soup([\"script\", \"style\"]):\n script.decompose()\n\n # Convert relative URLs to absolute\n for tag in soup.find_all([\"a\", \"img\"]):\n if tag.get(\"href\"):\n tag[\"href\"] = urljoin(url, tag[\"href\"])\n if tag.get(\"src\"):\n tag[\"src\"] = urljoin(url, tag[\"src\"])\n\n # Configure HTML to Markdown converter\n h2t = html2text.HTML2Text()\n h2t.body_width = 0 # No line wrapping\n h2t.ignore_images = not include_images\n h2t.ignore_emphasis = False\n h2t.ignore_links = False\n h2t.ignore_tables = False\n\n # Convert to markdown\n markdown = h2t.handle(str(soup))\n\n # Trim if max_length is specified\n if max_length and len(markdown) > max_length:\n markdown = markdown[:max_length] + \"\\n...(truncated)\"\n\n return markdown.strip()\n\n except httpx.RequestError as e:\n raise ValueError(f\"Failed to fetch webpage: {str(e)}\") from e\n except Exception as e:\n raise ValueError(f\"Error processing webpage: {str(e)}\") from e\n",
+ "name": "fetch_webpage",
+ "description": "Fetch a webpage and convert it to markdown format, with options for including images and limiting length",
+ "global_imports": [
+ "os",
+ "html2text",
+ { "module": "typing", "imports": ["Optional", "Dict"] },
+ "httpx",
+ { "module": "bs4", "imports": ["BeautifulSoup"] },
+ { "module": "html2text", "imports": ["HTML2Text"] },
+ { "module": "urllib.parse", "imports": ["urljoin"] }
+ ],
+ "has_cancellation_support": false
+ }
+ }
+ ]
+ }
+ },
+ {
+ "provider": "autogen_ext.tools.mcp.McpWorkbench",
+ "component_type": "workbench",
+ "version": 1,
+ "component_version": 1,
+ "description": "An MCP workbench that provides web content fetching capabilities using the mcp-server-fetch MCP server. Allows agents to fetch and read content from web pages and APIs.",
+ "label": "Web Content Fetch Workbench",
+ "config": {
+ "server_params": {
+ "command": "uvx",
+ "args": ["mcp-server-fetch"],
+ "encoding": "utf-8",
+ "encoding_error_handler": "strict",
+ "type": "StdioServerParams",
+ "read_timeout_seconds": 60.0
+ }
+ }
+ },
+ {
+ "provider": "autogen_ext.tools.mcp.McpWorkbench",
+ "component_type": "workbench",
+ "version": 1,
+ "component_version": 1,
+ "description": "An MCP workbench that connects to HTTP-based MCP servers using Server-Sent Events (SSE). Suitable for cloud-hosted MCP services and custom HTTP MCP implementations.",
+ "label": "HTTP Streamable MCP Workbench",
+ "config": {
+ "server_params": {
+ "type": "StreamableHttpServerParams",
+ "url": "http://localhost:8005/mcp",
+ "headers": {
+ "Authorization": "Bearer your-api-key",
+ "Content-Type": "application/json"
+ },
+ "timeout": 30.0,
+ "sse_read_timeout": 300.0,
+ "terminate_on_close": true
+ }
}
}
]
diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/detail.tsx b/python/packages/autogen-studio/frontend/src/components/views/gallery/detail.tsx
index 58cfcdba6..67f761731 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/detail.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/detail.tsx
@@ -1,5 +1,14 @@
-import React, { useState, useEffect } from "react";
-import { Tabs, Button, Tooltip, Drawer, Input } from "antd";
+import React, { useState, useEffect, useCallback, useRef } from "react";
+import {
+ Tabs,
+ Button,
+ Tooltip,
+ Drawer,
+ Input,
+ message,
+ Dropdown,
+ Tag,
+} from "antd";
import {
Package,
Users,
@@ -13,8 +22,14 @@ import {
Trash,
Plus,
Download,
+ Briefcase,
+ Code,
+ FormInput,
+ ChevronDown,
+ Server,
} from "lucide-react";
import { ComponentEditor } from "../teambuilder/builder/component-editor/component-editor";
+import { MonacoEditor } from "../monaco";
import { TruncatableText } from "../atoms";
import {
Component,
@@ -22,9 +37,48 @@ import {
ComponentTypes,
Gallery,
} from "../../types/datamodel";
+import {
+ getTemplatesForDropdown,
+ createComponentFromTemplateById,
+ getTeamTemplatesForDropdown,
+ createTeamFromTemplate,
+ getAgentTemplatesForDropdown,
+ createAgentFromTemplate,
+ getModelTemplatesForDropdown,
+ createModelFromTemplate,
+ getToolTemplatesForDropdown,
+ createToolFromTemplate,
+ getWorkbenchTemplatesForDropdown,
+ createWorkbenchFromTemplate,
+ getTerminationTemplatesForDropdown,
+ createTerminationFromTemplate,
+ type ComponentDropdownOption,
+} from "../../types/component-templates";
+import { isMcpWorkbench } from "../../types/guards";
import TextArea from "antd/es/input/TextArea";
+import Icon from "../../icons";
+import { AddComponentDropdown } from "../../shared";
-type CategoryKey = `${ComponentTypes}s`;
+type CategoryKey =
+ | "teams"
+ | "agents"
+ | "models"
+ | "tools"
+ | "workbenches"
+ | "terminations";
+
+// Helper function to get the correct category key for components
+const getCategoryKey = (componentType: ComponentTypes): CategoryKey => {
+ const mapping: Record<ComponentTypes, CategoryKey> = {
+ team: "teams",
+ agent: "agents",
+ model: "models",
+ tool: "tools",
+ workbench: "workbenches",
+ termination: "terminations",
+ };
+ return mapping[componentType];
+};
interface CardActions {
onEdit: (component: Component<ComponentConfig>, index: number) => void;
@@ -38,15 +92,26 @@ const ComponentCard: React.FC<
item: Component<ComponentConfig>;
index: number;
allowDelete: boolean;
+ disabled?: boolean;
}
-> = ({ item, onEdit, onDuplicate, onDelete, index, allowDelete }) => (
+> = ({
+ item,
+ onEdit,
+ onDuplicate,
+ onDelete,
+ index,
+ allowDelete,
+ disabled = false,
+}) => (
<div
- className="bg-secondary rounded overflow-hidden group h-full cursor-pointer"
- onClick={() => onEdit(item, index)}
+ className={`bg-secondary rounded overflow-hidden group h-full ${
+ disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"
+ }`}
+ onClick={() => !disabled && onEdit(item, index)}
>
<div className="px-4 py-3 flex items-center justify-between border-b border-tertiary">
<div className="text-xs text-secondary truncate flex-1">
- {item.provider}
+ {item.label || "Unnamed Component"}
</div>
<div className="flex gap-0">
{allowDelete && (
@@ -55,9 +120,10 @@ const ComponentCard: React.FC<
type="text"
className="h-6 w-6 flex items-center justify-center p-0 opacity-0 group-hover:opacity-100 transition-opacity text-red-500 hover:text-red-600"
icon={<Trash className="w-3.5 h-3.5" />}
+ disabled={disabled}
onClick={(e) => {
e.stopPropagation();
- onDelete(item, index);
+ if (!disabled) onDelete(item, index);
}}
/>
)}
@@ -66,9 +132,10 @@ const ComponentCard: React.FC<
type="text"
className="h-6 w-6 flex items-center justify-center p-0 opacity-0 group-hover:opacity-100 transition-opacity"
icon={<Copy className="w-3.5 h-3.5" />}
+ disabled={disabled}
onClick={(e) => {
e.stopPropagation();
- onDuplicate(item, index);
+ if (!disabled) onDuplicate(item, index);
}}
/>
<Button
@@ -76,15 +143,26 @@ const ComponentCard: React.FC<
type="text"
className="h-6 w-6 flex items-center justify-center p-0 opacity-0 group-hover:opacity-100 transition-opacity"
icon={<Edit className="w-3.5 h-3.5" />}
+ disabled={disabled}
onClick={(e) => {
e.stopPropagation();
- onEdit(item, index);
+ if (!disabled) onEdit(item, index);
}}
/>
</div>
</div>
<div className="p-4 pb-0 pt-3">
- <div className="text-base font-medium mb-2">{item.label}</div>
+ <div className="text-base font-medium mb-2 flex items-center gap-2">
+ {item.component_type === "workbench" && isMcpWorkbench(item) && (
+ <Icon icon="mcp" size={6} className="inline-block" />
+ )}{" "}
+ <span className="line-clamp-1">
+ {item.label || "Unnamed Component"}
+ </span>
+ </div>
+ <div className="text-xs text-secondary truncate mb-2">
+ {item.provider}
+ </div>
<div className="text-sm text-secondary line-clamp-2 mb-3 min-h-[40px]">
<TruncatableText
content={item.description || ""}
@@ -101,8 +179,9 @@ const ComponentGrid: React.FC<
{
items: Component<ComponentConfig>[];
title: string;
+ disabled?: boolean;
} & CardActions
-> = ({ items, title, ...actions }) => (
+> = ({ items, title, disabled = false, ...actions }) => (
<div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 auto-rows-fr">
{items.map((item, idx) => (
@@ -111,6 +190,7 @@ const ComponentGrid: React.FC<
item={item}
index={idx}
allowDelete={items.length > 1}
+ disabled={disabled}
{...actions}
/>
))}
@@ -124,23 +204,9 @@ const iconMap = {
tool: Wrench,
model: Brain,
termination: Timer,
+ workbench: Briefcase,
} as const;
-// Add default configurations for each component type
-const defaultConfigs: Record<ComponentTypes, ComponentConfig> = {
- team: { selector_prompt: "Default selector prompt", participants: [] } as any,
- agent: { name: "New Agent", description: "" } as any,
- model: { model: "gpt-3.5", api_key: "" } as any,
- tool: {
- source_code: "",
- name: "New Tool",
- description: "A new tool",
- global_imports: [],
- has_cancellation_support: false,
- },
- termination: { max_messages: 1 },
-};
-
export const GalleryDetail: React.FC<{
gallery: Gallery;
onSave: (updates: Partial<Gallery>) => void;
@@ -156,16 +222,29 @@ export const GalleryDetail: React.FC<{
} | null>(null);
const [activeTab, setActiveTab] = useState<ComponentTypes>("team");
const [isEditingDetails, setIsEditingDetails] = useState(false);
+ const [isJsonEditing, setIsJsonEditing] = useState(false);
+ const [workingCopy, setWorkingCopy] = useState<Gallery>(gallery);
+ const [jsonValue, setJsonValue] = useState<string>("");
+ const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
+ const [isDirty, setIsDirty] = useState(false);
const [tempName, setTempName] = useState(gallery.config.name);
const [tempDescription, setTempDescription] = useState(
gallery.config.metadata.description
);
+ const [messageApi, contextHolder] = message.useMessage();
+ const editorRef = useRef(null);
+
useEffect(() => {
setTempName(gallery.config.name);
setTempDescription(gallery.config.metadata.description);
+ setWorkingCopy(gallery);
+ setJsonValue(JSON.stringify(gallery, null, 2));
+ setHasUnsavedChanges(false);
+ setIsDirty(false);
setActiveTab("team");
setEditingComponent(null);
+ setIsJsonEditing(false);
}, [gallery.id]);
const updateGallery = (
@@ -174,44 +253,55 @@ export const GalleryDetail: React.FC<{
components: Component<ComponentConfig>[]
) => Component<ComponentConfig>[]
) => {
+ const currentGallery = isJsonEditing ? workingCopy : gallery;
const updatedGallery = {
- ...gallery,
+ ...currentGallery,
config: {
- ...gallery.config,
+ ...currentGallery.config,
components: {
- ...gallery.config.components,
- [category]: updater(gallery.config.components[category]),
+ ...currentGallery.config.components,
+ [category]: updater(currentGallery.config.components[category]),
},
},
};
- onSave(updatedGallery);
- onDirtyStateChange(true);
+
+ if (isJsonEditing) {
+ setWorkingCopy(updatedGallery);
+ } else {
+ onSave(updatedGallery);
+ onDirtyStateChange(true);
+ }
+ };
+
+ const handleJsonChange = (value: string) => {
+ setJsonValue(value);
+ setIsDirty(true);
};
const handlers = {
onEdit: (component: Component<ComponentConfig>, index: number) => {
setEditingComponent({
component,
- category: `${activeTab}s` as CategoryKey,
+ category: getCategoryKey(activeTab),
index,
});
},
onDuplicate: (component: Component<ComponentConfig>, index: number) => {
- const category = `${activeTab}s` as CategoryKey;
+ const category = getCategoryKey(activeTab);
const baseLabel = component.label?.replace(/_\d+$/, "");
- const components = gallery.config.components[category];
+ const components = gallery.config.components[category] || [];
const nextNumber =
Math.max(
...components
- .map((c) => {
+ .map((c: Component<ComponentConfig>) => {
const match = c.label?.match(
new RegExp(`^${baseLabel}_?(\\d+)?$`)
);
return match ? parseInt(match[1] || "0") : 0;
})
- .filter((n) => !isNaN(n)),
+ .filter((n: number) => !isNaN(n)),
0
) + 1;
@@ -222,37 +312,18 @@ export const GalleryDetail: React.FC<{
},
onDelete: (component: Component<ComponentConfig>, index: number) => {
- const category = `${activeTab}s` as CategoryKey;
+ const category = getCategoryKey(activeTab);
updateGallery(category, (components) =>
components.filter((_, i) => i !== index)
);
},
};
- const handleAdd = () => {
- const category = `${activeTab}s` as CategoryKey;
- const components = gallery.config.components[category];
- let newComponent: Component<ComponentConfig>;
- const newLabel = `New ${
- activeTab.charAt(0).toUpperCase() + activeTab.slice(1)
- }`;
-
- if (components.length > 0) {
- // Clone the entire component and just modify the label
- newComponent = {
- ...components[0], // This preserves all fields (provider, version, description, etc.)
- label: newLabel,
- };
- } else {
- // Only for empty categories, use default config
- newComponent = {
- provider: "new",
- component_type: activeTab,
- config: defaultConfigs[activeTab],
- label: newLabel,
- };
- }
-
+ // Handler for the reusable AddComponentDropdown
+ const handleComponentAdded = (
+ newComponent: Component<ComponentConfig>,
+ category: CategoryKey
+ ) => {
updateGallery(category, (components) => {
const newComponents = [...components, newComponent];
setEditingComponent({
@@ -264,6 +335,27 @@ export const GalleryDetail: React.FC<{
});
};
+ const handleAddWorkbench = (templateId: string) => {
+ const category = getCategoryKey("workbench");
+
+ try {
+ const newComponent = createWorkbenchFromTemplate(templateId);
+
+ updateGallery(category, (components) => {
+ const newComponents = [...components, newComponent];
+ setEditingComponent({
+ component: newComponent,
+ category,
+ index: newComponents.length - 1,
+ });
+ return newComponents;
+ });
+ } catch (error) {
+ console.error("Error creating workbench from template:", error);
+ messageApi.error("Failed to create workbench");
+ }
+ };
+
const handleComponentUpdate = (
updatedComponent: Component<ComponentConfig>
) => {
@@ -277,6 +369,21 @@ export const GalleryDetail: React.FC<{
setEditingComponent(null);
};
+ const handleJsonSave = () => {
+ try {
+ const updatedGallery = JSON.parse(jsonValue);
+ setWorkingCopy(updatedGallery);
+ onSave(updatedGallery);
+ onDirtyStateChange(true);
+ setIsJsonEditing(false);
+ setIsDirty(false);
+ messageApi.success("Gallery updated successfully!");
+ } catch (error) {
+ messageApi.error("Invalid JSON format. Please check your syntax.");
+ console.error("JSON parse error:", error);
+ }
+ };
+
const handleDetailsSave = () => {
const updatedGallery = {
...gallery,
@@ -309,6 +416,8 @@ export const GalleryDetail: React.FC<{
URL.revokeObjectURL(url);
};
+ const currentGallery = isJsonEditing ? workingCopy : gallery;
+
const tabItems = Object.entries(iconMap).map(([key, Icon]) => ({
key,
label: (
@@ -316,7 +425,11 @@ export const GalleryDetail: React.FC<{
<Icon className="w-5 h-5" />
{key.charAt(0).toUpperCase() + key.slice(1)}s
<span className="text-xs font-light text-secondary">
- ({gallery.config.components[`${key}s` as CategoryKey].length})
+ (
+ {currentGallery.config.components[
+ getCategoryKey(key as ComponentTypes)
+ ]?.length || 0}
+ )
</span>
</span>
),
@@ -324,25 +437,30 @@ export const GalleryDetail: React.FC<{
<div>
<div className="flex justify-between items-center mb-4">
<h3 className="text-base font-medium">
- {gallery.config.components[`${key}s` as CategoryKey].length}{" "}
- {gallery.config.components[`${key}s` as CategoryKey].length === 1
+ {currentGallery.config.components[
+ getCategoryKey(key as ComponentTypes)
+ ]?.length || 0}{" "}
+ {(currentGallery.config.components[
+ getCategoryKey(key as ComponentTypes)
+ ]?.length || 0) === 1
? key.charAt(0).toUpperCase() + key.slice(1)
: key.charAt(0).toUpperCase() + key.slice(1) + "s"}
</h3>
- <Button
- type="primary"
- icon={<Plus className="w-4 h-4" />}
- onClick={() => {
- setActiveTab(key as ComponentTypes);
- handleAdd();
- }}
- >
- {`Add ${key.charAt(0).toUpperCase() + key.slice(1)}`}
- </Button>
+ <AddComponentDropdown
+ componentType={key as ComponentTypes}
+ gallery={currentGallery}
+ onComponentAdded={handleComponentAdded}
+ disabled={isJsonEditing}
+ />
</div>
<ComponentGrid
- items={gallery.config.components[`${key}s` as CategoryKey]}
+ items={
+ currentGallery.config.components[
+ getCategoryKey(key as ComponentTypes)
+ ] || []
+ }
title={key}
+ disabled={isJsonEditing}
{...handlers}
/>
</div>
@@ -350,7 +468,9 @@ export const GalleryDetail: React.FC<{
}));
return (
- <div className="max-w-7xl mx-auto px-4">
+ <div className="max-w-7xl px-4">
+ {contextHolder}
+
<div className="relative h-64 rounded bg-secondary overflow-hidden mb-8">
<img
src="/images/bg/layeredbg.svg"
@@ -369,10 +489,10 @@ export const GalleryDetail: React.FC<{
/>
) : (
<h1 className="text-2xl font-medium text-primary">
- {gallery.config.name}
+ {currentGallery.config.name}
</h1>
)}
- {gallery.config.url && (
+ {currentGallery.config.url && (
<Tooltip title="Remote Gallery">
<Globe className="w-5 h-5 text-secondary" />
</Tooltip>
@@ -389,7 +509,7 @@ export const GalleryDetail: React.FC<{
) : (
<div className="flex flex-col gap-2">
<p className="text-secondary w-1/2 mt-2 line-clamp-2">
- {gallery.config.metadata.description}
+ {currentGallery.config.metadata.description}
</p>
<div className="flex gap-0">
<Tooltip title="Edit Gallery">
@@ -398,6 +518,7 @@ export const GalleryDetail: React.FC<{
onClick={() => setIsEditingDetails(true)}
type="text"
className="text-white hover:text-white/80"
+ disabled={isJsonEditing}
/>
</Tooltip>
<Tooltip title="Download Gallery">
@@ -408,6 +529,29 @@ export const GalleryDetail: React.FC<{
className="text-white hover:text-white/80"
/>
</Tooltip>
+ <Tooltip
+ title={isJsonEditing ? "Form Editor" : "JSON Editor"}
+ >
+ <Button
+ icon={
+ isJsonEditing ? (
+ <FormInput className="w-4 h-4" />
+ ) : (
+ <Code className="w-4 h-4" />
+ )
+ }
+ onClick={() => {
+ const newJsonMode = !isJsonEditing;
+ setIsJsonEditing(newJsonMode);
+ if (newJsonMode) {
+ setJsonValue(JSON.stringify(currentGallery, null, 2));
+ setIsDirty(false);
+ }
+ }}
+ type="text"
+ className="text-white hover:text-white/80"
+ />
+ </Tooltip>
</div>
</div>
)}
@@ -426,7 +570,7 @@ export const GalleryDetail: React.FC<{
<div className="bg-tertiary backdrop-blur rounded p-2 flex items-center gap-2">
<Package className="w-4 h-4 text-secondary" />
<span className="text-sm">
- {Object.values(gallery.config.components).reduce(
+ {Object.values(currentGallery.config.components).reduce(
(sum, arr) => sum + arr.length,
0
)}{" "}
@@ -434,18 +578,56 @@ export const GalleryDetail: React.FC<{
</span>
</div>
<div className="bg-tertiary backdrop-blur rounded p-2 text-sm">
- v{gallery.config.metadata.version}
+ v{currentGallery.config.metadata.version}
</div>
</div>
</div>
</div>
- <Tabs
- items={tabItems}
- className="gallery-tabs"
- size="large"
- onChange={(key) => setActiveTab(key as ComponentTypes)}
- />
+ {isJsonEditing ? (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <h2 className="text-xl font-medium">JSON Editor</h2>
+ {isDirty && (
+ <span className="text-orange-500 text-sm">
+ • Unsaved changes
+ </span>
+ )}
+ </div>
+ <div className="flex gap-2">
+ <Button
+ onClick={() => {
+ setIsJsonEditing(false);
+ setIsDirty(false);
+ setJsonValue(JSON.stringify(gallery, null, 2));
+ }}
+ >
+ Cancel
+ </Button>
+ <Button type="primary" onClick={handleJsonSave}>
+ Save Changes
+ </Button>
+ </div>
+ </div>
+ <div className="h-[600px] border border-secondary rounded">
+ <MonacoEditor
+ editorRef={editorRef}
+ value={jsonValue}
+ onChange={handleJsonChange}
+ language="json"
+ minimap={true}
+ />
+ </div>
+ </div>
+ ) : (
+ <Tabs
+ items={tabItems}
+ className="gallery-tabs"
+ size="large"
+ onChange={(key) => setActiveTab(key as ComponentTypes)}
+ />
+ )}
<Drawer
title="Edit Component"
diff --git a/python/packages/autogen-studio/frontend/src/components/views/gallery/sidebar.tsx b/python/packages/autogen-studio/frontend/src/components/views/gallery/sidebar.tsx
index 09fb9dd0c..dda3e0ab4 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/gallery/sidebar.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/gallery/sidebar.tsx
@@ -137,7 +137,9 @@ export const GallerySidebar: React.FC<GallerySidebarProps> = ({
<div className="flex items-center justify-between min-w-0">
<div className="flex items-center gap-2 min-w-0 flex-1">
<div className="truncate flex-1">
- <span className="font-medium">{gallery.config.name}</span>
+ <span className="font-medium text-sm">
+ {gallery.config.name}
+ </span>
</div>
{gallery.config.url && (
<Tooltip title="Remote Gallery">
diff --git a/python/packages/autogen-studio/frontend/src/components/views/labs/labs/api.ts b/python/packages/autogen-studio/frontend/src/components/views/labs/labs/api.ts
new file mode 100644
index 000000000..111082c0e
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/labs/labs/api.ts
@@ -0,0 +1,84 @@
+// api.ts for Tool Maker Lab
+import { BaseAPI } from "../../../utils/baseapi";
+
+export interface ToolMakerEvent {
+ status: string;
+ content: string;
+}
+
+export interface ToolComponentModel {
+ provider: string;
+ component_type: string;
+ version: number;
+ component_version: number;
+ description: string;
+ label: string;
+ config: any;
+}
+
+export type ToolMakerStreamMessage =
+ | { event: ToolMakerEvent }
+ | { component: ToolComponentModel }
+ | { error: string };
+
+export class ToolMakerAPI extends BaseAPI {
+ ws: WebSocket | null = null;
+
+ // Helper for WebSocket URL construction (similar to MCP implementation)
+ private getWebSocketBaseUrl(url: string): string {
+ try {
+ let baseUrl = url.replace(/(^\w+:|^)\/\//, "");
+ if (baseUrl.startsWith("localhost")) {
+ baseUrl = baseUrl.replace("/api", "");
+ } else if (baseUrl === "/api") {
+ baseUrl = window.location.host;
+ } else {
+ baseUrl = baseUrl.replace("/api", "").replace(/\/$/, "");
+ }
+ return baseUrl;
+ } catch (error) {
+ throw new Error("Invalid server URL configuration");
+ }
+ }
+
+ connect(
+ onMessage: (msg: ToolMakerStreamMessage) => void,
+ onError?: (err: any) => void,
+ onClose?: () => void
+ ) {
+ // Use the same server URL logic as other APIs
+ const serverUrl = this.getBaseUrl(); // e.g., "/api" or "http://localhost:8081/api"
+ const baseUrl = this.getWebSocketBaseUrl(serverUrl);
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ const wsUrl = `${protocol}//${baseUrl}/api/maker/tool`;
+ this.ws = new window.WebSocket(wsUrl);
+ this.ws.onmessage = (event) => {
+ try {
+ const data = JSON.parse(event.data);
+ onMessage(data);
+ } catch (e) {
+ if (onError) onError(e);
+ }
+ };
+ this.ws.onerror = (event) => {
+ if (onError) onError(event);
+ };
+ this.ws.onclose = () => {
+ if (onClose) onClose();
+ };
+ }
+
+ sendDescription(description: string) {
+ if (this.ws && this.ws.readyState === 1) {
+ this.ws.send(JSON.stringify({ description }));
+ }
+ }
+
+ close() {
+ if (this.ws) {
+ this.ws.close();
+ }
+ }
+}
+
+export const toolMakerAPI = new ToolMakerAPI();
diff --git a/python/packages/autogen-studio/frontend/src/components/views/labs/labs/guides.tsx b/python/packages/autogen-studio/frontend/src/components/views/labs/labs/guides.tsx
index 76c20b5b1..3864f5862 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/labs/labs/guides.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/labs/labs/guides.tsx
@@ -1,6 +1,7 @@
import React from "react";
import { Lab } from "../types";
import ComponentLab from "./component";
+import ToolMakerLab from "./tool";
interface LabContentProps {
lab: Lab;
@@ -14,7 +15,8 @@ export const LabContent: React.FC<LabContentProps> = ({ lab }) => {
switch (lab.id) {
case "python-setup":
return <ComponentLab />;
-
+ case "tool-maker":
+ return <ToolMakerLab />;
default:
return (
<div className="text-secondary">
diff --git a/python/packages/autogen-studio/frontend/src/components/views/labs/labs/tool.tsx b/python/packages/autogen-studio/frontend/src/components/views/labs/labs/tool.tsx
new file mode 100644
index 000000000..7165ea824
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/labs/labs/tool.tsx
@@ -0,0 +1,134 @@
+import React, { useState, useRef } from "react";
+import { Input, Button, Alert, Spin, Tag } from "antd";
+import { SendOutlined } from "@ant-design/icons";
+import {
+ toolMakerAPI,
+ ToolMakerEvent,
+ ToolComponentModel,
+ ToolMakerStreamMessage,
+} from "./api";
+
+const ToolMakerLab: React.FC = () => {
+ const [description, setDescription] = useState("");
+ const [events, setEvents] = useState<ToolMakerEvent[]>([]);
+ const [component, setComponent] = useState<ToolComponentModel | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const wsRef = useRef<typeof toolMakerAPI | null>(null);
+
+ const exampleTools = [
+ "A tool that fetches the content of a web page",
+ "A calculator tool that performs mathematical operations",
+ "A tool that generates QR codes from text",
+ "A tool that converts text to speech",
+ "A tool that extracts text from images (OCR)",
+ "A tool that validates email addresses",
+ "A tool that generates secure random passwords",
+ "A tool that converts currencies using live exchange rates",
+ ];
+
+ const handleExampleClick = (example: string) => {
+ setDescription(example);
+ };
+
+ const handleStart = () => {
+ setEvents([]);
+ setComponent(null);
+ setError(null);
+ setLoading(true);
+ wsRef.current = toolMakerAPI;
+ wsRef.current.connect(
+ (msg: ToolMakerStreamMessage) => {
+ if ("event" in msg) {
+ setEvents((prev) => [...prev, msg.event]);
+ } else if ("component" in msg) {
+ setComponent(msg.component);
+ setLoading(false);
+ wsRef.current?.close();
+ } else if ("error" in msg) {
+ setError(msg.error);
+ setLoading(false);
+ wsRef.current?.close();
+ }
+ },
+ (err) => {
+ setError("WebSocket error: " + err);
+ setLoading(false);
+ },
+ () => {
+ setLoading(false);
+ }
+ );
+ setTimeout(() => {
+ wsRef.current?.sendDescription(description);
+ }, 200); // Give ws time to connect
+ };
+
+ return (
+ <div className="">
+ <h1 className="text-2xl font-bold mb-6">Tool Maker (Experimental)</h1>
+ <p className="mb-4 text-secondary">
+ This lab allows you to create and test new tools using natural language
+ descriptions.
+ </p>
+
+ <div className="mb-4">
+ <p className="text-sm font-medium mb-2 text-secondary">
+ Try these examples:
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {exampleTools.map((example, idx) => (
+ <Tag
+ key={idx}
+ className="cursor-pointer hover:bg-primary/10 transition-colors"
+ onClick={() => handleExampleClick(example)}
+ >
+ {example}
+ </Tag>
+ ))}
+ </div>
+ </div>
+ <div className="flex gap-2 mb-4">
+ <Input
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="Describe your tool (e.g. 'A tool that fetches the content of a web page')"
+ onPressEnter={handleStart}
+ disabled={loading}
+ />
+ <Button
+ type="primary"
+ icon={<SendOutlined />}
+ onClick={handleStart}
+ loading={loading}
+ disabled={!description.trim() || loading}
+ >
+ Create
+ </Button>
+ </div>
+ {error && <Alert type="error" message={error} className="mb-4" />}
+ {loading && <Spin className="mb-4" />}
+ <div className="mb-4">
+ {events.map((event, idx) => (
+ <Alert
+ key={idx}
+ type="info"
+ message={event.status}
+ description={event.content}
+ className="mb-2"
+ />
+ ))}
+ </div>
+ {component && (
+ <div className="border rounded p-4 bg-secondary/10">
+ <h2 className="font-semibold mb-2">Generated Tool</h2>
+ <pre className="bg-secondary/20 p-2 rounded text-xs overflow-x-auto mb-2">
+ {JSON.stringify(component, null, 2)}
+ </pre>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default ToolMakerLab;
diff --git a/python/packages/autogen-studio/frontend/src/components/views/labs/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/labs/manager.tsx
index f39f41f83..44fcce977 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/labs/manager.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/labs/manager.tsx
@@ -30,6 +30,10 @@ export const LabsManager: React.FC = () => {
}
}, [labs, currentLab]);
+ useEffect(() => {
+ setLabs(defaultLabs);
+ }, []);
+
return (
<div className="relative flex h-full w-full">
{/* Sidebar */}
diff --git a/python/packages/autogen-studio/frontend/src/components/views/labs/types.tsx b/python/packages/autogen-studio/frontend/src/components/views/labs/types.tsx
index dc7bb85ba..3d6374b6e 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/labs/types.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/labs/types.tsx
@@ -5,9 +5,14 @@ export interface Lab {
}
export const defaultLabs: Lab[] = [
+ // {
+ // id: "component-builder",
+ // title: "Component Builder",
+ // type: "python",
+ // },
{
- id: "component-builder",
- title: "Component Builder",
+ id: "tool-maker",
+ title: "Tool Maker",
type: "python",
},
];
diff --git a/python/packages/autogen-studio/frontend/src/components/views/mcp/api.ts b/python/packages/autogen-studio/frontend/src/components/views/mcp/api.ts
new file mode 100644
index 000000000..56729a489
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/mcp/api.ts
@@ -0,0 +1,750 @@
+import {
+ Gallery,
+ Component,
+ McpWorkbenchConfig,
+ McpServerParams,
+} from "../../types/datamodel";
+import { BaseAPI } from "../../utils/baseapi";
+import { getServerUrl } from "../../utils/utils";
+
+// MCP-specific interfaces for server operations
+// MCP types matching backend exactly (native MCP types)
+export interface Tool {
+ name: string;
+ description?: string | null;
+ inputSchema: {
+ [key: string]: any;
+ };
+ annotations?: {
+ title?: string | null;
+ readOnlyHint?: boolean | null;
+ destructiveHint?: boolean | null;
+ idempotentHint?: boolean | null;
+ openWorldHint?: boolean | null;
+ } | null;
+}
+
+export interface CallToolResult {
+ content: Array<{
+ type: "text" | "image" | "resource";
+ text?: string;
+ data?: string;
+ mimeType?: string;
+ resource?: any;
+ annotations?: any;
+ }>;
+ isError?: boolean;
+}
+
+export interface ListToolsResponse {
+ status: boolean;
+ message: string;
+ tools?: Tool[];
+}
+
+export interface CallToolResponse {
+ status: boolean;
+ message: string;
+ result?: CallToolResult;
+}
+
+export interface ServerCapabilities {
+ tools?: {
+ listChanged?: boolean;
+ };
+ resources?: {
+ subscribe?: boolean;
+ listChanged?: boolean;
+ };
+ prompts?: {
+ listChanged?: boolean;
+ };
+ logging?: {};
+ sampling?: {};
+}
+
+export interface GetCapabilitiesResponse {
+ status: boolean;
+ message: string;
+ capabilities?: ServerCapabilities;
+}
+
+export class McpAPI extends BaseAPI {
+ // Gallery management methods (existing functionality)
+ async listGalleries(userId: string): Promise<Gallery[]> {
+ const response = await fetch(
+ `${this.getBaseUrl()}/gallery/?user_id=${userId}`,
+ {
+ headers: this.getHeaders(),
+ }
+ );
+ const data = await response.json();
+ if (!data.status)
+ throw new Error(data.message || "Failed to fetch galleries");
+ return data.data;
+ }
+
+ async getGallery(galleryId: number, userId: string): Promise<Gallery> {
+ const response = await fetch(
+ `${this.getBaseUrl()}/gallery/${galleryId}?user_id=${userId}`,
+ {
+ headers: this.getHeaders(),
+ }
+ );
+ const data = await response.json();
+ if (!data.status)
+ throw new Error(data.message || "Failed to fetch gallery");
+ return data.data;
+ }
+
+ // Helper function to extract MCP workbenches from a gallery
+ extractMcpWorkbenches(gallery: Gallery): Component<McpWorkbenchConfig>[] {
+ return (
+ gallery.config.components.workbenches?.filter(
+ (workbench): workbench is Component<McpWorkbenchConfig> =>
+ workbench.provider.includes("McpWorkbench") ||
+ (workbench.config as any)?.server_params !== undefined
+ ) || []
+ );
+ }
+
+ // MCP Server operations (new functionality)
+ async listResources(serverParams: McpServerParams) {
+ const response = await fetch(`${this.getBaseUrl()}/mcp/resources/list`, {
+ method: "POST",
+ headers: this.getHeaders(),
+ body: JSON.stringify({ server_params: serverParams }),
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.message || "Failed to list MCP resources");
+ }
+
+ return data;
+ }
+
+ async getResource(serverParams: McpServerParams, uri: string) {
+ const response = await fetch(`${this.getBaseUrl()}/mcp/resources/get`, {
+ method: "POST",
+ headers: this.getHeaders(),
+ body: JSON.stringify({
+ server_params: serverParams,
+ uri: uri,
+ }),
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.message || "Failed to get MCP resource");
+ }
+
+ return data;
+ }
+
+ async listPrompts(serverParams: McpServerParams) {
+ const response = await fetch(`${this.getBaseUrl()}/mcp/prompts/list`, {
+ method: "POST",
+ headers: this.getHeaders(),
+ body: JSON.stringify({ server_params: serverParams }),
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.message || "Failed to list MCP prompts");
+ }
+
+ return data;
+ }
+
+ async getPrompt(
+ serverParams: McpServerParams,
+ name: string,
+ promptArgs?: Record<string, any>
+ ) {
+ const response = await fetch(`${this.getBaseUrl()}/mcp/prompts/get`, {
+ method: "POST",
+ headers: this.getHeaders(),
+ body: JSON.stringify({
+ server_params: serverParams,
+ name: name,
+ arguments: promptArgs || {},
+ }),
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.message || "Failed to get MCP prompt");
+ }
+
+ return data;
+ }
+
+ async getCapabilities(
+ serverParams: McpServerParams
+ ): Promise<GetCapabilitiesResponse> {
+ const response = await fetch(`${this.getBaseUrl()}/mcp/capabilities/get`, {
+ method: "POST",
+ headers: this.getHeaders(),
+ body: JSON.stringify({ server_params: serverParams }),
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.message || "Failed to get MCP capabilities");
+ }
+
+ return data;
+ }
+
+ async listTools(serverParams: McpServerParams): Promise<ListToolsResponse> {
+ const response = await fetch(`${this.getBaseUrl()}/mcp/tools/list`, {
+ method: "POST",
+ headers: this.getHeaders(),
+ body: JSON.stringify({ server_params: serverParams }),
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.message || "Failed to list MCP tools");
+ }
+
+ return data;
+ }
+
+ async callTool(
+ serverParams: McpServerParams,
+ toolName: string,
+ toolArguments: Record<string, any>
+ ): Promise<CallToolResponse> {
+ const response = await fetch(`${this.getBaseUrl()}/mcp/tools/call`, {
+ method: "POST",
+ headers: this.getHeaders(),
+ body: JSON.stringify({
+ server_params: serverParams,
+ tool_name: toolName,
+ arguments: toolArguments,
+ }),
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.message || "Failed to call MCP tool");
+ }
+
+ return data;
+ }
+
+ async healthCheck(): Promise<{ status: boolean; message: string }> {
+ const response = await fetch(`${this.getBaseUrl()}/mcp/health`, {
+ method: "GET",
+ headers: this.getHeaders(),
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.message || "MCP health check failed");
+ }
+
+ return data;
+ }
+
+ // Test MCP server connection
+ async testMcpConnection(
+ workbench: Component<McpWorkbenchConfig>
+ ): Promise<boolean> {
+ try {
+ // Use the health check or list tools to test connection
+ if (workbench.config.server_params) {
+ const result = await this.listTools(workbench.config.server_params);
+ return result.status;
+ }
+ return false;
+ } catch (error) {
+ return false;
+ }
+ }
+
+ // WebSocket connection management
+ async createWebSocketConnection(serverParams: McpServerParams): Promise<any> {
+ const response = await fetch(`${this.getBaseUrl()}/mcp/ws/connect`, {
+ method: "POST",
+ headers: this.getHeaders(),
+ body: JSON.stringify({ server_params: serverParams }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ throw new Error(
+ `HTTP ${response.status}: ${
+ errorText || "Failed to create WebSocket connection"
+ }`
+ );
+ }
+
+ try {
+ const responseText = await response.text();
+ return JSON.parse(responseText);
+ } catch (jsonError) {
+ throw new Error(
+ `Invalid JSON response from server. Check if the MCP route is properly configured.`
+ );
+ }
+ }
+}
+
+// WebSocket-based MCP functionality
+export interface McpWebSocketState {
+ connected: boolean;
+ connecting: boolean;
+ capabilities: ServerCapabilities | null;
+ sessionId: string | null;
+ error: string | null;
+ lastActivity: Date | null;
+ activityMessages: McpActivityMessage[];
+ pendingElicitations: ElicitationRequest[];
+}
+
+export interface McpWebSocketMessage {
+ type:
+ | "connected"
+ | "initializing"
+ | "initialized"
+ | "operation_result"
+ | "operation_error"
+ | "error"
+ | "pong"
+ | "mcp_activity"
+ | "elicitation_request";
+ session_id?: string;
+ capabilities?: ServerCapabilities;
+ operation?: string;
+ data?: any;
+ error?: string;
+ message?: string;
+ timestamp?: string;
+ // Activity message fields
+ activity_type?: "protocol" | "error" | "sampling" | "elicitation";
+ details?: any;
+ // Elicitation fields
+ request_id?: string;
+ requestedSchema?: any;
+}
+
+export interface McpActivityMessage {
+ id: string;
+ activity_type: "protocol" | "error" | "sampling" | "elicitation";
+ message: string;
+ details?: any;
+ session_id?: string;
+ timestamp: Date;
+}
+
+export interface McpOperationMessage {
+ type: "operation";
+ operation: string;
+ tool_name?: string;
+ arguments?: Record<string, any>;
+ uri?: string;
+ name?: string;
+}
+
+export interface UseMcpWebSocketReturn {
+ state: McpWebSocketState;
+ connect: () => Promise<void>;
+ executeOperation: (
+ operation: Omit<McpOperationMessage, "type">
+ ) => Promise<any>;
+ ping: () => void;
+ disconnect: () => void;
+}
+
+export class McpWebSocketClient {
+ private wsRef: WebSocket | null = null;
+ private operationPromises: Map<
+ string,
+ { resolve: (value: any) => void; reject: (error: any) => void }
+ > = new Map();
+ private operationTimers: Map<string, Set<NodeJS.Timeout>> = new Map();
+ private reconnectAttempts = 0;
+ private maxReconnectAttempts = 5;
+ private baseReconnectDelay = 1000;
+ private reconnectTimeout: NodeJS.Timeout | null = null;
+ private currentState: McpWebSocketState = {
+ connected: false,
+ connecting: false,
+ capabilities: null,
+ sessionId: null,
+ error: null,
+ lastActivity: null,
+ activityMessages: [],
+ pendingElicitations: [],
+ };
+
+ constructor(
+ private serverParams: McpServerParams,
+ private onStateChange: (state: Partial<McpWebSocketState>) => void
+ ) {}
+
+ private updateState(partialState: Partial<McpWebSocketState>) {
+ this.currentState = { ...this.currentState, ...partialState };
+ this.onStateChange(partialState);
+ }
+
+ // Helper method to clear all timers for a specific operation type
+ private clearTimersForOperation(operationType: string) {
+ const timers = this.operationTimers.get(operationType);
+ if (timers) {
+ timers.forEach((timerId) => clearTimeout(timerId));
+ timers.clear();
+ }
+ }
+
+ // Helper for WebSocket URL construction (similar to chat implementation)
+ private getWebSocketBaseUrl(url: string): string {
+ try {
+ let baseUrl = url.replace(/(^\w+:|^)\/\//, "");
+ if (baseUrl.startsWith("localhost")) {
+ baseUrl = baseUrl.replace("/api", "");
+ } else if (baseUrl === "/api") {
+ baseUrl = window.location.host;
+ } else {
+ baseUrl = baseUrl.replace("/api", "").replace(/\/$/, "");
+ }
+ return baseUrl;
+ } catch (error) {
+ throw new Error("Invalid server URL configuration");
+ }
+ }
+
+ async connect(): Promise<void> {
+ this.updateState({ connecting: true, error: null });
+
+ try {
+ // First, get the WebSocket connection URL using proper API construction
+ const mcpApiInstance = mcpAPI;
+ const connectionData = await mcpApiInstance.createWebSocketConnection(
+ this.serverParams
+ );
+
+ if (!connectionData.status) {
+ throw new Error(
+ connectionData.message || "Failed to create WebSocket connection"
+ );
+ }
+
+ const { session_id, websocket_url } = connectionData;
+
+ // Construct WebSocket URL using the correct server URL (not window.location.host)
+ // This handles cases where backend runs on different port (e.g., 8081 vs 8000)
+ const serverUrl = getServerUrl(); // e.g., "/api" or "http://localhost:8081/api"
+ const baseUrl = this.getWebSocketBaseUrl(serverUrl);
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ const wsUrl = `${protocol}//${baseUrl}${websocket_url}`;
+
+ // Create WebSocket connection
+ const ws = new WebSocket(wsUrl);
+ this.wsRef = ws;
+
+ ws.onopen = () => {
+ this.updateState({
+ connected: true,
+ connecting: false,
+ sessionId: session_id,
+ error: null,
+ lastActivity: new Date(),
+ });
+ this.reconnectAttempts = 0;
+ };
+
+ ws.onmessage = (event) => {
+ try {
+ const message: McpWebSocketMessage = JSON.parse(event.data);
+ console.log("Received MCP WebSocket message:", message);
+ this.updateState({ lastActivity: new Date() });
+
+ switch (message.type) {
+ case "connected":
+ break;
+
+ case "initializing":
+ break;
+
+ case "initialized":
+ if (message.capabilities) {
+ this.updateState({ capabilities: message.capabilities });
+ }
+ break;
+
+ case "operation_result":
+ // Handle operation results
+ if (message.operation) {
+ const operationKey = message.operation;
+ const promise = this.operationPromises.get(operationKey);
+ if (promise) {
+ // Clear all timers for this operation type to prevent interference
+ this.clearTimersForOperation(operationKey);
+ // Resolve the promise
+ promise.resolve(message.data);
+ this.operationPromises.delete(operationKey);
+ }
+ }
+ break;
+
+ case "operation_error":
+ // Handle operation-specific errors - reject the specific operation
+ if (message.operation) {
+ const promise = this.operationPromises.get(message.operation);
+ if (promise) {
+ // Clear all timers for this operation type to prevent interference
+ this.clearTimersForOperation(message.operation);
+ // Reject the promise
+ promise.reject(
+ new Error(message.error || "Operation failed")
+ );
+ this.operationPromises.delete(message.operation);
+ }
+ }
+ break;
+
+ case "error":
+ // Handle connection/session-level errors - these affect the whole session
+ this.updateState({
+ error: message.error || "Connection error",
+ });
+ break;
+
+ case "pong":
+ // Handle pong response
+ break;
+
+ case "mcp_activity":
+ // Handle activity messages
+ if (message.message && message.activity_type) {
+ const activityMessage: McpActivityMessage = {
+ id: `${Date.now()}-${Math.random()
+ .toString(36)
+ .substr(2, 9)}`,
+ activity_type: message.activity_type,
+ message: message.message,
+ details: message.details,
+ session_id: message.session_id,
+ timestamp: message.timestamp
+ ? new Date(message.timestamp)
+ : new Date(),
+ };
+
+ // Update state with new activity message
+ this.updateState({
+ activityMessages: [
+ ...this.currentState.activityMessages,
+ activityMessage,
+ ],
+ });
+ }
+ break;
+
+ case "elicitation_request":
+ // Handle elicitation requests
+ if (message.request_id && message.message) {
+ const elicitationRequest: ElicitationRequest = {
+ request_id: message.request_id,
+ message: message.message,
+ requestedSchema: message.requestedSchema,
+ session_id:
+ message.session_id || this.currentState.sessionId || "",
+ timestamp: message.timestamp || new Date().toISOString(),
+ };
+
+ // Add to pending elicitations
+ this.updateState({
+ pendingElicitations: [
+ ...this.currentState.pendingElicitations,
+ elicitationRequest,
+ ],
+ });
+ } else {
+ console.error(
+ "Invalid elicitation request - missing request_id or message:",
+ message
+ );
+ }
+ break;
+
+ default:
+ // Unknown message type - silently ignore
+ break;
+ }
+ } catch (error) {
+ // Error parsing WebSocket message - silently ignore
+ }
+ };
+
+ ws.onerror = (error) => {
+ this.updateState({
+ error: "WebSocket connection error",
+ connected: false,
+ connecting: false,
+ });
+ };
+
+ ws.onclose = (event) => {
+ this.updateState({
+ connected: false,
+ connecting: false,
+ });
+
+ // // Attempt to reconnect if not manually closed
+ // if (
+ // event.code !== 1000 &&
+ // this.reconnectAttempts < this.maxReconnectAttempts
+ // ) {
+ // const delay =
+ // this.baseReconnectDelay * Math.pow(2, this.reconnectAttempts);
+
+ // this.reconnectTimeout = setTimeout(() => {
+ // this.reconnectAttempts++;
+ // this.connect();
+ // console.log(
+ // `Reconnecting... Attempt ${this.reconnectAttempts} after ${delay}ms`
+ // );
+ // }, delay);
+ // }
+ };
+ } catch (error) {
+ this.updateState({
+ error: error instanceof Error ? error.message : "Connection failed",
+ connected: false,
+ connecting: false,
+ });
+ }
+ }
+
+ async executeOperation(
+ operation: Omit<McpOperationMessage, "type">
+ ): Promise<any> {
+ return new Promise((resolve, reject) => {
+ if (!this.wsRef || this.wsRef.readyState !== WebSocket.OPEN) {
+ reject(new Error("WebSocket not connected"));
+ return;
+ }
+
+ const operationKey = operation.operation;
+
+ // Store the promise for this operation
+ this.operationPromises.set(operationKey, { resolve, reject });
+
+ // Send the operation message
+ const message: McpOperationMessage = {
+ type: "operation",
+ ...operation,
+ };
+
+ try {
+ this.wsRef.send(JSON.stringify(message));
+ } catch (error) {
+ this.operationPromises.delete(operationKey);
+ reject(error);
+ }
+
+ // Set a timeout for the operation and track it by operation type
+ const timerId = setTimeout(() => {
+ if (this.operationPromises.has(operationKey)) {
+ this.operationPromises.delete(operationKey);
+ reject(new Error("Operation timeout"));
+ }
+ }, 120000); // 120 second timeout (2 minutes) for long-running operations
+
+ // Track this timer by operation type
+ if (!this.operationTimers.has(operationKey)) {
+ this.operationTimers.set(operationKey, new Set());
+ }
+ this.operationTimers.get(operationKey)!.add(timerId);
+ });
+ }
+
+ ping(): void {
+ if (this.wsRef && this.wsRef.readyState === WebSocket.OPEN) {
+ this.wsRef.send(JSON.stringify({ type: "ping" }));
+ }
+ }
+
+ disconnect(): void {
+ if (this.reconnectTimeout) {
+ clearTimeout(this.reconnectTimeout);
+ this.reconnectTimeout = null;
+ }
+
+ if (this.wsRef) {
+ this.wsRef.close();
+ this.wsRef = null;
+ }
+
+ // Reject all pending operations and clear all timers
+ this.operationPromises.forEach(({ reject }) => {
+ reject(new Error("WebSocket connection closed"));
+ });
+ this.operationPromises.clear();
+
+ // Clear all operation timers
+ this.operationTimers.forEach((timers) => {
+ timers.forEach((timerId) => clearTimeout(timerId));
+ timers.clear();
+ });
+ this.operationTimers.clear();
+
+ this.updateState({
+ connected: false,
+ connecting: false,
+ sessionId: null,
+ capabilities: null,
+ error: null,
+ });
+ }
+
+ sendElicitationResponse(response: ElicitationResponse): void {
+ if (this.wsRef && this.wsRef.readyState === WebSocket.OPEN) {
+ try {
+ this.wsRef.send(JSON.stringify(response));
+
+ // Remove the elicitation from pending list
+ this.updateState({
+ pendingElicitations: this.currentState.pendingElicitations.filter(
+ (req) => req.request_id !== response.request_id
+ ),
+ });
+ } catch (error) {
+ console.error("Failed to send elicitation response:", error);
+ }
+ } else {
+ console.error(
+ "WebSocket not connected - cannot send elicitation response"
+ );
+ }
+ }
+
+ clearActivityMessages(): void {
+ this.updateState({
+ activityMessages: [],
+ });
+ }
+}
+
+export const mcpAPI = new McpAPI();
+
+// Elicitation interfaces
+export interface ElicitationRequest {
+ request_id: string;
+ message: string;
+ requestedSchema?: any;
+ session_id: string;
+ timestamp: string;
+}
+
+export interface ElicitationResponse {
+ type: "elicitation_response";
+ request_id: string;
+ action: "accept" | "decline" | "cancel";
+ data?: Record<string, any>;
+ session_id: string;
+}
diff --git a/python/packages/autogen-studio/frontend/src/components/views/mcp/create-modal.tsx b/python/packages/autogen-studio/frontend/src/components/views/mcp/create-modal.tsx
new file mode 100644
index 000000000..8cd869fea
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/mcp/create-modal.tsx
@@ -0,0 +1,416 @@
+import React, { useState } from "react";
+import {
+ Modal,
+ Form,
+ Input,
+ Select,
+ Button,
+ Space,
+ Collapse,
+ Alert,
+} from "antd";
+import { Plus, Trash2, Server, PlusCircle, MinusCircle } from "lucide-react";
+import type { McpServer } from "./types";
+import type {
+ McpServerParams,
+ StdioServerParams,
+ SseServerParams,
+ StreamableHttpServerParams,
+} from "../../types/datamodel";
+
+const { TextArea } = Input;
+const { Option } = Select;
+const { Panel } = Collapse;
+
+interface McpServerCreateModalProps {
+ open: boolean;
+ onCancel: () => void;
+ onCreateServer: (server: Omit<McpServer, "id">) => void;
+}
+
+export const McpServerCreateModal: React.FC<McpServerCreateModalProps> = ({
+ open,
+ onCancel,
+ onCreateServer,
+}) => {
+ const [form] = Form.useForm();
+ const [serverType, setServerType] = useState<
+ "StdioServerParams" | "SseServerParams" | "StreamableHttpServerParams"
+ >("StdioServerParams");
+ const [args, setArgs] = useState<string[]>([]);
+ const [envVars, setEnvVars] = useState<Array<{ key: string; value: string }>>(
+ []
+ );
+
+ const handleSubmit = async () => {
+ try {
+ const values = await form.validateFields();
+
+ let serverParams: McpServerParams;
+
+ switch (serverType) {
+ case "StdioServerParams":
+ serverParams = {
+ type: "StdioServerParams",
+ command: values.command,
+ args: args.length > 0 ? args : undefined,
+ env:
+ envVars.length > 0
+ ? Object.fromEntries(envVars.map((env) => [env.key, env.value]))
+ : undefined,
+ read_timeout_seconds: values.read_timeout_seconds || 5,
+ } as StdioServerParams;
+ break;
+
+ case "SseServerParams":
+ serverParams = {
+ type: "SseServerParams",
+ url: values.url,
+ timeout: values.timeout || 30,
+ sse_read_timeout: values.sse_read_timeout || 300,
+ headers: values.headers ? JSON.parse(values.headers) : undefined,
+ } as SseServerParams;
+ break;
+
+ case "StreamableHttpServerParams":
+ serverParams = {
+ type: "StreamableHttpServerParams",
+ url: values.url,
+ timeout: values.timeout || 30,
+ sse_read_timeout: values.sse_read_timeout || 300,
+ headers: values.headers ? JSON.parse(values.headers) : undefined,
+ terminate_on_close: values.terminate_on_close || false,
+ } as StreamableHttpServerParams;
+ break;
+
+ default:
+ throw new Error("Invalid server type");
+ }
+
+ const newServer: Omit<McpServer, "id"> = {
+ name: values.name,
+ description: values.description,
+ serverParams,
+ isConnected: false,
+ };
+
+ onCreateServer(newServer);
+ handleReset();
+ } catch (error) {
+ console.error("Validation failed:", error);
+ }
+ };
+
+ const handleReset = () => {
+ form.resetFields();
+ setArgs([]);
+ setEnvVars([]);
+ setServerType("StdioServerParams");
+ };
+
+ const handleCancel = () => {
+ handleReset();
+ onCancel();
+ };
+
+ const addArg = () => {
+ setArgs([...args, ""]);
+ };
+
+ const removeArg = (index: number) => {
+ setArgs(args.filter((_, i) => i !== index));
+ };
+
+ const updateArg = (index: number, value: string) => {
+ const newArgs = [...args];
+ newArgs[index] = value;
+ setArgs(newArgs);
+ };
+
+ const addEnvVar = () => {
+ setEnvVars([...envVars, { key: "", value: "" }]);
+ };
+
+ const removeEnvVar = (index: number) => {
+ setEnvVars(envVars.filter((_, i) => i !== index));
+ };
+
+ const updateEnvVar = (
+ index: number,
+ field: "key" | "value",
+ value: string
+ ) => {
+ const newEnvVars = [...envVars];
+ newEnvVars[index] = { ...newEnvVars[index], [field]: value };
+ setEnvVars(newEnvVars);
+ };
+
+ return (
+ <Modal
+ title={
+ <div className="flex items-center gap-2">
+ <Server className="w-5 h-5 text-accent" />
+ <span>Add MCP Server</span>
+ </div>
+ }
+ open={open}
+ onCancel={handleCancel}
+ footer={[
+ <Button key="cancel" onClick={handleCancel}>
+ Cancel
+ </Button>,
+ <Button key="submit" type="primary" onClick={handleSubmit}>
+ Add Server
+ </Button>,
+ ]}
+ width={600}
+ destroyOnClose
+ >
+ <Form
+ form={form}
+ layout="vertical"
+ initialValues={{
+ read_timeout_seconds: 5,
+ timeout: 30,
+ sse_read_timeout: 300,
+ terminate_on_close: false,
+ }}
+ >
+ {/* Basic Information */}
+ <Collapse defaultActiveKey={["basic"]} ghost>
+ <Panel header="Basic Information" key="basic">
+ <Form.Item
+ label="Server Name"
+ name="name"
+ rules={[
+ { required: true, message: "Please enter a server name" },
+ ]}
+ >
+ <Input placeholder="e.g., My MCP Server" />
+ </Form.Item>
+
+ <Form.Item label="Description" name="description">
+ <TextArea
+ rows={2}
+ placeholder="Optional description of the server"
+ />
+ </Form.Item>
+
+ <Form.Item
+ label="Server Type"
+ name="type"
+ rules={[
+ { required: true, message: "Please select a server type" },
+ ]}
+ >
+ <Select
+ value={serverType}
+ onChange={setServerType}
+ placeholder="Select server type"
+ >
+ <Option value="StdioServerParams">
+ <div className="flex items-center gap-2">
+ <span>Standard I/O</span>
+ <small className="text-gray-500">
+ (Local command execution)
+ </small>
+ </div>
+ </Option>
+ <Option value="SseServerParams">
+ <div className="flex items-center gap-2">
+ <span>Server-Sent Events</span>
+ <small className="text-gray-500">(HTTP SSE)</small>
+ </div>
+ </Option>
+ <Option value="StreamableHttpServerParams">
+ <div className="flex items-center gap-2">
+ <span>Streamable HTTP</span>
+ <small className="text-gray-500">(HTTP streaming)</small>
+ </div>
+ </Option>
+ </Select>
+ </Form.Item>
+ </Panel>
+ </Collapse>
+
+ {/* Server Configuration */}
+ <Collapse className="mt-4" ghost>
+ <Panel header="Server Configuration" key="config">
+ {serverType === "StdioServerParams" && (
+ <div className="space-y-4">
+ <Form.Item
+ label="Command"
+ name="command"
+ rules={[
+ { required: true, message: "Please enter a command" },
+ ]}
+ >
+ <Input placeholder="e.g., uvx, python, node" />
+ </Form.Item>
+
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <label className="block text-sm font-medium">
+ Arguments
+ </label>
+ <Button
+ type="dashed"
+ size="small"
+ icon={<PlusCircle className="w-4 h-4" />}
+ onClick={addArg}
+ >
+ Add Argument
+ </Button>
+ </div>
+
+ {args.length === 0 ? (
+ <div className="text-sm text-gray-500 italic p-3 border border-dashed rounded">
+ No arguments. Click "Add Argument" to add command line
+ arguments.
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {args.map((arg, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <span className="text-xs text-gray-500 w-8">
+ {index}
+ </span>
+ <Input
+ value={arg}
+ onChange={(e) => updateArg(index, e.target.value)}
+ placeholder={`Argument ${index}`}
+ className="flex-1"
+ />
+ <Button
+ type="text"
+ size="small"
+ icon={<Trash2 className="w-4 h-4" />}
+ onClick={() => removeArg(index)}
+ className="text-red-500 hover:text-red-700"
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <label className="block text-sm font-medium">
+ Environment Variables
+ </label>
+ <Button
+ type="dashed"
+ size="small"
+ icon={<PlusCircle className="w-4 h-4" />}
+ onClick={addEnvVar}
+ >
+ Add Variable
+ </Button>
+ </div>
+
+ {envVars.length === 0 ? (
+ <div className="text-sm text-gray-500 italic p-3 border border-dashed rounded">
+ No environment variables. Click "Add Variable" to add
+ environment variables.
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {envVars.map((env, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <Input
+ value={env.key}
+ onChange={(e) =>
+ updateEnvVar(index, "key", e.target.value)
+ }
+ placeholder="Variable name"
+ className="flex-1"
+ />
+ <span>=</span>
+ <Input
+ value={env.value}
+ onChange={(e) =>
+ updateEnvVar(index, "value", e.target.value)
+ }
+ placeholder="Variable value"
+ className="flex-1"
+ />
+ <Button
+ type="text"
+ size="small"
+ icon={<MinusCircle className="w-4 h-4" />}
+ onClick={() => removeEnvVar(index)}
+ className="text-red-500 hover:text-red-700"
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <Form.Item
+ label="Read Timeout (seconds)"
+ name="read_timeout_seconds"
+ >
+ <Input type="number" min={1} />
+ </Form.Item>
+ </div>
+ )}
+
+ {(serverType === "SseServerParams" ||
+ serverType === "StreamableHttpServerParams") && (
+ <div className="space-y-4">
+ <Form.Item
+ label="Server URL"
+ name="url"
+ rules={[
+ { required: true, message: "Please enter a server URL" },
+ { type: "url", message: "Please enter a valid URL" },
+ ]}
+ >
+ <Input placeholder="https://your-mcp-server.com" />
+ </Form.Item>
+
+ <Form.Item label="Timeout (seconds)" name="timeout">
+ <Input type="number" min={1} />
+ </Form.Item>
+
+ <Form.Item
+ label="SSE Read Timeout (seconds)"
+ name="sse_read_timeout"
+ >
+ <Input type="number" min={1} />
+ </Form.Item>
+
+ <Form.Item label="Headers (JSON)" name="headers">
+ <TextArea
+ rows={3}
+ placeholder='{"Authorization": "Bearer token", "Content-Type": "application/json"}'
+ />
+ </Form.Item>
+
+ {serverType === "StreamableHttpServerParams" && (
+ <Form.Item
+ label="Terminate on Close"
+ name="terminate_on_close"
+ valuePropName="checked"
+ >
+ <Input type="checkbox" />
+ </Form.Item>
+ )}
+ </div>
+ )}
+ </Panel>
+ </Collapse>
+
+ <Alert
+ className="mt-4"
+ message="Server Configuration"
+ description="Configure your MCP server connection parameters. For StdIO servers, specify the command and arguments. For HTTP-based servers, provide the server URL and connection settings."
+ type="info"
+ showIcon
+ />
+ </Form>
+ </Modal>
+ );
+};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/mcp/detail.tsx b/python/packages/autogen-studio/frontend/src/components/views/mcp/detail.tsx
new file mode 100644
index 000000000..8f8af4ce3
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/mcp/detail.tsx
@@ -0,0 +1,42 @@
+import React from "react";
+import { Card, Button, Alert, Badge, Descriptions } from "antd";
+import {
+ Server,
+ Play,
+ Settings,
+ CheckCircle,
+ XCircle,
+ Info,
+} from "lucide-react";
+import type { Component, McpWorkbenchConfig } from "../../types/datamodel";
+import { WorkbenchFields } from "../teambuilder/builder/component-editor/fields/workbench";
+
+interface McpDetailProps {
+ workbench: Component<McpWorkbenchConfig>;
+ onTestConnection: () => void;
+}
+
+const McpDetail: React.FC<McpDetailProps> = ({
+ workbench,
+ onTestConnection,
+}) => {
+ const serverParams = workbench.config.server_params;
+ const serverType =
+ serverParams?.type?.replace("ServerParams", "") || "Unknown";
+
+ return (
+ <div className=" ">
+ <WorkbenchFields
+ component={workbench}
+ defaultPanelKey={["testing"]}
+ readonly
+ onChange={() => {
+ // In the playground, we don't allow editing - this is read-only
+ // The user would need to go to the Team Builder to make changes
+ }}
+ />
+ </div>
+ );
+};
+
+export default McpDetail;
diff --git a/python/packages/autogen-studio/frontend/src/components/views/mcp/index.ts b/python/packages/autogen-studio/frontend/src/components/views/mcp/index.ts
new file mode 100644
index 000000000..0b4aad48b
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/mcp/index.ts
@@ -0,0 +1,12 @@
+export { default as McpManager } from "./manager";
+export { default as McpSidebar } from "./sidebar";
+export { default as McpDetail } from "./detail";
+export {
+ mcpAPI,
+ Tool,
+ CallToolResult,
+ ListToolsResponse,
+ CallToolResponse,
+} from "./api";
+
+export { default } from "./manager";
diff --git a/python/packages/autogen-studio/frontend/src/components/views/mcp/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/mcp/manager.tsx
new file mode 100644
index 000000000..7a297a450
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/mcp/manager.tsx
@@ -0,0 +1,215 @@
+import React, { useCallback, useEffect, useState, useContext } from "react";
+import { message } from "antd";
+import { ChevronRight } from "lucide-react";
+import { appContext } from "../../../hooks/provider";
+import McpSidebar from "./sidebar";
+import McpDetail from "./detail";
+import { mcpAPI } from "./api";
+import { galleryAPI } from "../gallery/api";
+import type {
+ Gallery,
+ Component,
+ McpWorkbenchConfig,
+} from "../../types/datamodel";
+import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
+
+const McpManager: React.FC = () => {
+ const [isLoading, setIsLoading] = useState(false);
+ const [currentWorkbench, setCurrentWorkbench] =
+ useState<Component<McpWorkbenchConfig> | null>(null);
+ const [isSidebarOpen, setIsSidebarOpen] = useState(() => {
+ if (typeof window !== "undefined") {
+ const stored = localStorage.getItem("mcpSidebar");
+ return stored !== null ? JSON.parse(stored) : true;
+ }
+ return true;
+ });
+
+ const { user } = useContext(appContext);
+ const [messageApi, contextHolder] = message.useMessage();
+
+ // Persist sidebar state
+ useEffect(() => {
+ if (typeof window !== "undefined") {
+ localStorage.setItem("mcpSidebar", JSON.stringify(isSidebarOpen));
+ }
+ }, [isSidebarOpen]);
+
+ // Handle initial URL params
+ useEffect(() => {
+ const params = new URLSearchParams(window.location.search);
+ const galleryId = params.get("galleryId");
+ const workbenchIndex = params.get("workbenchIndex");
+
+ if (galleryId && workbenchIndex && !currentWorkbench) {
+ // Pass URL params to sidebar to handle initial selection
+ // The sidebar will handle the actual workbench loading based on these params
+ }
+ }, [currentWorkbench]);
+
+ // Handle browser back/forward
+ useEffect(() => {
+ const handleLocationChange = () => {
+ const params = new URLSearchParams(window.location.search);
+ const galleryId = params.get("galleryId");
+ const workbenchIndex = params.get("workbenchIndex");
+
+ if (!galleryId || !workbenchIndex) {
+ // No URL params, clear current workbench
+ if (currentWorkbench) {
+ setCurrentWorkbench(null);
+ }
+ }
+ };
+
+ window.addEventListener("popstate", handleLocationChange);
+ return () => window.removeEventListener("popstate", handleLocationChange);
+ }, [currentWorkbench]);
+
+ const handleSelectWorkbench = (
+ workbench: Component<McpWorkbenchConfig> | null,
+ galleryId?: number,
+ workbenchIndex?: number
+ ) => {
+ setCurrentWorkbench(workbench);
+
+ // Update URL when a workbench is selected
+ if (workbench && galleryId !== undefined && workbenchIndex !== undefined) {
+ const params = new URLSearchParams(window.location.search);
+ params.set("galleryId", galleryId.toString());
+ params.set("workbenchIndex", workbenchIndex.toString());
+ window.history.pushState({}, "", `?${params.toString()}`);
+ } else if (!workbench) {
+ // Clear URL params when no workbench is selected
+ window.history.pushState({}, "", window.location.pathname);
+ }
+ };
+
+ const handleGalleryUpdate = async (updatedGallery: Gallery) => {
+ if (!user?.id || !updatedGallery.id) return;
+
+ try {
+ setIsLoading(true);
+ // Sanitize the gallery data by removing timestamps that shouldn't be updated
+ const sanitizedUpdates = {
+ ...updatedGallery,
+ created_at: undefined,
+ updated_at: undefined,
+ };
+ await galleryAPI.updateGallery(
+ updatedGallery.id,
+ sanitizedUpdates,
+ user.id
+ );
+ messageApi.success("Gallery updated successfully");
+ } catch (error) {
+ console.error("Failed to update gallery:", error);
+ messageApi.error("Failed to update gallery");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleTestConnection = async (
+ workbench: Component<McpWorkbenchConfig>
+ ) => {
+ try {
+ setIsLoading(true);
+ const isConnected = await mcpAPI.testMcpConnection(workbench);
+
+ if (isConnected) {
+ messageApi.success("Connection test successful");
+ } else {
+ messageApi.error("Connection test failed");
+ }
+ } catch (error) {
+ console.error("Connection test failed:", error);
+ messageApi.error("Connection test failed");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ if (!user?.id) {
+ return (
+ <div className="flex items-center justify-center h-[calc(100vh-120px)] text-secondary">
+ Please log in to use the MCP Playground
+ </div>
+ );
+ }
+
+ return (
+ <div className="relative flex h-full w-full">
+ {contextHolder}
+
+ {/* Sidebar */}
+ <div
+ className={`absolute left-0 top-0 h-full transition-all duration-200 ease-in-out ${
+ isSidebarOpen ? "w-64" : "w-12"
+ }`}
+ >
+ <McpSidebar
+ isOpen={isSidebarOpen}
+ onToggle={() => setIsSidebarOpen(!isSidebarOpen)}
+ onSelectWorkbench={handleSelectWorkbench}
+ isLoading={isLoading}
+ currentWorkbench={currentWorkbench}
+ onGalleryUpdate={handleGalleryUpdate}
+ />
+ </div>
+
+ {/* Main Content */}
+ <div
+ className={`flex-1 transition-all -mr-6 duration-200 ${
+ isSidebarOpen ? "ml-64" : "ml-12"
+ }`}
+ >
+ <div className="p-4 pt-2 h-[calc(100%-60px)]">
+ <div className="text-xs text-secondary mb-4 border border-dashed rounded-md p-2 ">
+ <ExclamationTriangleIcon className="w-4 h-4 inline-block mr-1 text-warning text-orange-500" />{" "}
+ MCP Playground is an experimental view for testing MCP Servers in
+ your Gallery{" "}
+ </div>
+ {/* Breadcrumb */}
+ <div className="flex items-center gap-2 mb-4 text-sm">
+ <span className="text-primary font-medium">MCP Playground</span>
+ {currentWorkbench && (
+ <>
+ <ChevronRight className="w-4 h-4 text-secondary" />
+ <span className="text-secondary">{currentWorkbench.label}</span>
+ </>
+ )}
+ </div>
+
+ {/* Content Area */}
+ {isLoading && !currentWorkbench ? (
+ <div className="flex items-center justify-center h-[calc(100vh-120px)] text-secondary">
+ Loading...
+ </div>
+ ) : currentWorkbench ? (
+ <div className=" h-[calc(100vh-235px)] scroll overflow-auto">
+ {" "}
+ <McpDetail
+ workbench={currentWorkbench}
+ onTestConnection={() => handleTestConnection(currentWorkbench)}
+ />
+ </div>
+ ) : (
+ <div className="flex items-center justify-center h-[calc(100vh-120px)] text-secondary">
+ <div className="text-center">
+ <h3 className="text-lg font-medium mb-2">
+ Welcome to MCP Playground
+ </h3>
+ <p className="text-secondary mb-4">
+ Select an MCP workbench from the sidebar to start testing
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default McpManager;
diff --git a/python/packages/autogen-studio/frontend/src/components/views/mcp/sidebar.tsx b/python/packages/autogen-studio/frontend/src/components/views/mcp/sidebar.tsx
new file mode 100644
index 000000000..14e91685a
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/mcp/sidebar.tsx
@@ -0,0 +1,370 @@
+import React, { useState, useEffect, useContext, useCallback } from "react";
+import { Button, Tooltip, Select } from "antd";
+import {
+ PanelLeftClose,
+ PanelLeftOpen,
+ Package,
+ RefreshCw,
+ Info,
+ Globe,
+} from "lucide-react";
+import { appContext } from "../../../hooks/provider";
+import { mcpAPI } from "./api";
+import type {
+ Gallery,
+ Component,
+ McpWorkbenchConfig,
+} from "../../types/datamodel";
+import { getRelativeTimeString } from "../atoms";
+import Icon from "../../icons";
+import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
+
+const { Option } = Select;
+
+interface McpSidebarProps {
+ isOpen: boolean;
+ onToggle: () => void;
+ onSelectWorkbench: (
+ workbench: Component<McpWorkbenchConfig> | null,
+ galleryId?: number,
+ workbenchIndex?: number
+ ) => void;
+ isLoading?: boolean;
+ currentWorkbench: Component<McpWorkbenchConfig> | null;
+ onGalleryUpdate?: (gallery: Gallery) => void;
+}
+
+export const McpSidebar: React.FC<McpSidebarProps> = ({
+ isOpen,
+ onToggle,
+ onSelectWorkbench,
+ isLoading = false,
+ currentWorkbench,
+ onGalleryUpdate,
+}) => {
+ const [galleries, setGalleries] = useState<Gallery[]>([]);
+ const [selectedGallery, setSelectedGallery] = useState<Gallery | null>(null);
+ const [mcpWorkbenches, setMcpWorkbenches] = useState<
+ Component<McpWorkbenchConfig>[]
+ >([]);
+ const [selectedWorkbenchIndex, setSelectedWorkbenchIndex] =
+ useState<number>(-1);
+ const [loadingGalleries, setLoadingGalleries] = useState(false);
+
+ const { user } = useContext(appContext);
+
+ // Helper function to get a unique React key for rendering
+ const getWorkbenchKey = (
+ workbench: Component<McpWorkbenchConfig>,
+ index: number
+ ) => {
+ // Use a hash of the workbench config plus index to ensure uniqueness
+ const configStr = JSON.stringify(workbench.config);
+ return `${workbench.provider}-${
+ workbench.label || "unnamed"
+ }-${configStr.slice(0, 20)}-${index}`;
+ };
+
+ // Handle gallery selection
+ const handleGallerySelect = useCallback((gallery: Gallery) => {
+ setSelectedGallery(gallery);
+ if (gallery.id) {
+ localStorage.setItem("mcp-view-gallery", gallery.id.toString());
+ }
+
+ // Extract MCP workbenches from the selected gallery
+ const workbenches = mcpAPI.extractMcpWorkbenches(gallery);
+ setMcpWorkbenches(workbenches);
+ // Reset selection - let the effect handle workbench selection
+ setSelectedWorkbenchIndex(-1);
+ }, []);
+
+ // Load galleries on component mount
+ const loadGalleries = useCallback(async () => {
+ if (!user?.id) return;
+
+ try {
+ setLoadingGalleries(true);
+ const galleriesData = await mcpAPI.listGalleries(user.id);
+ setGalleries(galleriesData);
+
+ // Select gallery based on URL params first, then localStorage, then first gallery
+ const params = new URLSearchParams(window.location.search);
+ const urlGalleryId = params.get("galleryId");
+ const savedGalleryId = localStorage.getItem("mcp-view-gallery");
+ let galleryToSelect = galleriesData[0];
+
+ if (urlGalleryId) {
+ // Prioritize URL parameter
+ const urlGallery = galleriesData.find(
+ (g) => g.id?.toString() === urlGalleryId
+ );
+ if (urlGallery) {
+ galleryToSelect = urlGallery;
+ }
+ } else if (savedGalleryId) {
+ // Fall back to localStorage
+ const savedGallery = galleriesData.find(
+ (g) => g.id?.toString() === savedGalleryId
+ );
+ if (savedGallery) {
+ galleryToSelect = savedGallery;
+ }
+ }
+
+ if (galleryToSelect) {
+ // Set gallery and workbenches, but don't trigger selection here
+ setSelectedGallery(galleryToSelect);
+ if (galleryToSelect.id) {
+ localStorage.setItem(
+ "mcp-view-gallery",
+ galleryToSelect.id.toString()
+ );
+ }
+
+ const workbenches = mcpAPI.extractMcpWorkbenches(galleryToSelect);
+ setMcpWorkbenches(workbenches);
+
+ // Let the effect below handle the workbench selection
+ }
+ } catch (error) {
+ console.error("Failed to load galleries:", error);
+ } finally {
+ setLoadingGalleries(false);
+ }
+ }, [user?.id]);
+
+ useEffect(() => {
+ loadGalleries();
+ }, [loadGalleries]);
+
+ // Handle workbench selection after galleries/workbenches are loaded
+ useEffect(() => {
+ if (mcpWorkbenches.length > 0 && selectedGallery && !loadingGalleries) {
+ // Check for URL parameters to restore workbench selection
+ const params = new URLSearchParams(window.location.search);
+ const urlGalleryId = params.get("galleryId");
+ const urlWorkbenchIndex = params.get("workbenchIndex");
+
+ let indexToSelect = 0; // Default to first workbench
+
+ // If URL params match current gallery, try to select the specified workbench
+ if (
+ urlGalleryId &&
+ urlWorkbenchIndex &&
+ selectedGallery.id?.toString() === urlGalleryId
+ ) {
+ const urlIndex = parseInt(urlWorkbenchIndex);
+ if (urlIndex >= 0 && urlIndex < mcpWorkbenches.length) {
+ indexToSelect = urlIndex;
+ }
+ }
+
+ // Only update if selection has changed
+ if (selectedWorkbenchIndex !== indexToSelect) {
+ setSelectedWorkbenchIndex(indexToSelect);
+ onSelectWorkbench(
+ mcpWorkbenches[indexToSelect],
+ selectedGallery.id,
+ indexToSelect
+ );
+ }
+ } else if (
+ mcpWorkbenches.length === 0 &&
+ selectedWorkbenchIndex !== -1 &&
+ !loadingGalleries
+ ) {
+ // No workbenches available, clear selection
+ setSelectedWorkbenchIndex(-1);
+ onSelectWorkbench(null);
+ }
+ }, [mcpWorkbenches, selectedGallery, onSelectWorkbench, loadingGalleries]); // Add loadingGalleries to prevent premature execution
+
+ // Render collapsed state
+ if (!isOpen) {
+ return (
+ <div className="h-full border-r border-secondary">
+ <div className="p-2 -ml-2">
+ <Tooltip title={`MCP Workbenches (${mcpWorkbenches.length})`}>
+ <button
+ onClick={onToggle}
+ className="p-2 rounded-md hover:bg-secondary hover:text-accent text-secondary transition-colors focus:outline-none focus:ring-2 focus:ring-accent focus:ring-opacity-50"
+ >
+ <PanelLeftOpen strokeWidth={1.5} className="h-6 w-6" />
+ </button>
+ </Tooltip>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="h-full border-r border-secondary bg-primary">
+ {/* Header */}
+ <div className="flex items-center justify-between pt-0 p-4 pl-2 pr-2 border-b border-secondary">
+ <div className="flex sticky items-center gap-2">
+ <span className="text-primary font-medium">MCP Playground</span>
+ <span className="px-2 py-0.5 text-xs bg-accent/10 text-accent rounded">
+ {mcpWorkbenches.length}
+ </span>
+ </div>
+ <Tooltip title="Close Sidebar">
+ <button
+ onClick={onToggle}
+ className="p-2 rounded-md hover:bg-secondary hover:text-accent text-secondary transition-colors focus:outline-none focus:ring-2 focus:ring-accent focus:ring-opacity-50"
+ >
+ <PanelLeftClose strokeWidth={1.5} className="h-6 w-6" />
+ </button>
+ </Tooltip>
+ </div>
+
+ {/* Gallery Selection */}
+ <div className="p-4 pl-2 border-b border-secondary">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-sm text-secondary">Gallery</span>
+ <Tooltip title="Refresh galleries">
+ <Button
+ size="small"
+ icon={
+ loadingGalleries ? (
+ <RefreshCw className="w-3 h-3 animate-spin" />
+ ) : (
+ <RefreshCw className="w-3 h-3" />
+ )
+ }
+ className="border-0 hover:bg-secondary"
+ onClick={loadGalleries}
+ disabled={loadingGalleries}
+ />
+ </Tooltip>
+ </div>
+ <Select
+ className="w-full"
+ placeholder="Select a gallery"
+ value={selectedGallery?.id}
+ onChange={(galleryId) => {
+ const gallery = galleries.find((g) => g.id === galleryId);
+ if (gallery) handleGallerySelect(gallery);
+ }}
+ loading={loadingGalleries}
+ >
+ {galleries.map((gallery) => (
+ <Option key={gallery.id} value={gallery.id}>
+ <div className="flex items-center gap-2">
+ <Package className="w-3 h-3" />
+ <span>{gallery.config.name}</span>
+ {gallery.config.url && (
+ <Globe className="w-3 h-3 text-secondary" />
+ )}
+ </div>
+ </Option>
+ ))}
+ </Select>
+ </div>
+
+ {/* Section Label */}
+ <div className="py-2 flex text-sm text-secondary px-4">
+ <div className="flex">
+ MCP Workbenches
+ {isLoading && <RefreshCw className="w-4 h-4 ml-2 animate-spin" />}
+ </div>
+ </div>
+
+ {/* Workbenches List */}
+ {!selectedGallery && (
+ <div className="p-2 mr-2 text-center text-secondary text-sm border border-dashed rounded mx-4">
+ <Info className="w-4 h-4 inline-block mr-1.5 -mt-0.5" />
+ Select a gallery to view MCP workbenches
+ </div>
+ )}
+
+ {selectedGallery && mcpWorkbenches.length === 0 && (
+ <div className="p-2 mr-2 text-center text-secondary text-sm border border-dashed rounded ml-2">
+ <Info className="w-4 h-4 inline-block mr-1.5 -mt-0.5" />
+ No MCP workbenches found in this gallery
+ </div>
+ )}
+
+ <div className="scroll overflow-y-auto h-[calc(100%-230px)]">
+ {mcpWorkbenches.map((workbench, index) => {
+ const workbenchKey = getWorkbenchKey(workbench, index);
+ const isSelected = index === selectedWorkbenchIndex;
+
+ return (
+ <div key={workbenchKey} className="relative border-secondary">
+ <div
+ className={`absolute top-1 left-0.5 z-50 h-[calc(100%-8px)] w-1 bg-opacity-80 rounded ${
+ isSelected ? "bg-accent" : "bg-tertiary"
+ }`}
+ />
+ <div
+ className={`group ml-1 flex flex-col p-3 rounded-l cursor-pointer hover:bg-secondary ${
+ isSelected
+ ? "border-accent bg-secondary"
+ : "border-transparent"
+ }`}
+ onClick={() => {
+ setSelectedWorkbenchIndex(index);
+ onSelectWorkbench(workbench, selectedGallery?.id, index);
+ }}
+ >
+ {/* Workbench Name and Actions Row */}
+ <div className="flex items-center justify-between min-w-0">
+ <div className="flex items-center gap-2 min-w-0 flex-1">
+ <Icon
+ icon="mcp"
+ size={4}
+ className="w-4 h-4 text-accent flex-shrink-0"
+ />
+ <div className="truncate flex-1 text-sm">
+ <span className="font-medium">{workbench.label}</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Workbench Details */}
+ <div className="mt-1 text-sm text-secondary">
+ <div className="flex items-center gap-2">
+ <span className="truncate text-xs">
+ {workbench.config.server_params?.type?.replace(
+ "ServerParams",
+ ""
+ ) || "Unknown Type"}
+ </span>
+ </div>
+ {/* {workbench.description && (
+ <div className="mt-1 text-xs text-secondary truncate">
+ {workbench.description}
+ </div>
+ )} */}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Footer */}
+ {selectedGallery && (
+ <div className="p-3 border-t border-secondary text-sm text-secondary">
+ <div className="flex items-center justify-between">
+ <span className="truncate flex-1">
+ {selectedGallery.config.name}
+ </span>
+ <span className="ml-2 flex-shrink-0">
+ {mcpWorkbenches.length} MCP workbench
+ {mcpWorkbenches.length !== 1 ? "es" : ""}
+ </span>
+ </div>
+ {selectedGallery.updated_at && (
+ <div className="text-xs text-tertiary mt-1">
+ Updated {getRelativeTimeString(selectedGallery.updated_at)}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default McpSidebar;
diff --git a/python/packages/autogen-studio/frontend/src/components/views/mcp/types.ts b/python/packages/autogen-studio/frontend/src/components/views/mcp/types.ts
new file mode 100644
index 000000000..30b25f2c0
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/mcp/types.ts
@@ -0,0 +1,16 @@
+import type { McpServerParams } from "../../types/datamodel";
+
+// Define a more complete MCP Server interface for the playground
+export interface McpServer {
+ id: string;
+ name: string;
+ description?: string;
+ serverParams: McpServerParams;
+ isConnected?: boolean;
+ lastConnected?: string;
+ tools?: Array<{
+ name: string;
+ description: string;
+ schema?: any;
+ }>;
+}
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx
index 61fcc6cda..f4b394f54 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/chat.tsx
@@ -19,7 +19,7 @@ import ChatInput from "./chatinput";
import { teamAPI } from "../../teambuilder/api";
import { sessionAPI } from "../api";
import RunView from "./runview";
-import { TIMEOUT_CONFIG } from "./types";
+import { createTimeoutConfig } from "./types";
import {
ChevronRight,
MessagesSquare,
@@ -28,6 +28,7 @@ import {
} from "lucide-react";
import SessionDropdown from "./sessiondropdown";
import { RcFile } from "antd/es/upload";
+import { useSettingsStore } from "../../settings/store";
const logo = require("../../../../images/landing/welcome.svg").default;
interface ChatViewProps {
@@ -79,6 +80,13 @@ export default function ChatView({
const [teamConfig, setTeamConfig] =
React.useState<Component<TeamConfig> | null>(null);
+ // Get settings for timeout configuration
+ const { uiSettings } = useSettingsStore();
+ const timeoutConfig = React.useMemo(
+ () => createTimeoutConfig(uiSettings.human_input_timeout_minutes || 3),
+ [uiSettings.human_input_timeout_minutes]
+ );
+
const inputTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
const activeSocketRef = React.useRef<WebSocket | null>(null);
@@ -235,8 +243,8 @@ export default function ChatView({
socket.send(
JSON.stringify({
type: "stop",
- reason: TIMEOUT_CONFIG.DEFAULT_MESSAGE,
- code: TIMEOUT_CONFIG.WEBSOCKET_CODE,
+ reason: timeoutConfig.DEFAULT_MESSAGE,
+ code: timeoutConfig.WEBSOCKET_CODE,
})
);
setCurrentRun((prev) =>
@@ -244,12 +252,12 @@ export default function ChatView({
? {
...prev,
status: "stopped",
- error_message: TIMEOUT_CONFIG.DEFAULT_MESSAGE,
+ error_message: timeoutConfig.DEFAULT_MESSAGE,
}
: null
);
}
- }, TIMEOUT_CONFIG.DURATION_MS);
+ }, timeoutConfig.DURATION_MS);
return {
...current,
@@ -429,10 +437,12 @@ export default function ChatView({
created_at: new Date().toISOString(),
status: "created", // Start with created status
messages: [],
- task: {
- content: query,
- source: "user",
- },
+ task: [
+ {
+ content: query,
+ source: "user",
+ },
+ ],
team_result: null,
error_message: undefined,
});
@@ -474,11 +484,13 @@ export default function ChatView({
created_at: new Date().toISOString(),
status: "active",
- task: createMessage(
- { content: query, source: "user" },
- runId,
- session.id || 0
- ).config,
+ task: [
+ createMessage(
+ { content: query, source: "user" },
+ runId,
+ session.id || 0
+ ).config,
+ ],
team_result: null,
messages: [],
error_message: undefined,
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/inputrequest.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/inputrequest.tsx
index 1526e4788..4df0285b3 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/inputrequest.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/inputrequest.tsx
@@ -1,6 +1,7 @@
import React, { useEffect, useRef } from "react";
import { SendHorizontal, Loader2, Clock } from "lucide-react";
-import { TIMEOUT_CONFIG } from "./types";
+import { createTimeoutConfig } from "./types";
+import { useSettingsStore } from "../../settings/store";
interface InputRequestProps {
prompt: string;
@@ -17,7 +18,15 @@ const InputRequestView: React.FC<InputRequestProps> = ({
}) => {
const [response, setResponse] = React.useState("");
const [isSubmitting, setIsSubmitting] = React.useState(false);
- const [timeLeft, setTimeLeft] = React.useState(TIMEOUT_CONFIG.DURATION_SEC);
+
+ // Get timeout from settings
+ const { uiSettings } = useSettingsStore();
+ const timeoutConfig = React.useMemo(
+ () => createTimeoutConfig(uiSettings.human_input_timeout_minutes || 3),
+ [uiSettings.human_input_timeout_minutes]
+ );
+
+ const [timeLeft, setTimeLeft] = React.useState(timeoutConfig.DURATION_SEC);
const [hasInteracted, setHasInteracted] = React.useState(false);
const inputRef = React.useRef<HTMLInputElement>(null);
const timerRef = useRef<NodeJS.Timeout>();
@@ -84,7 +93,7 @@ const InputRequestView: React.FC<InputRequestProps> = ({
};
const getTimeoutWarningClass = () => {
- if (timeLeft < TIMEOUT_CONFIG.WARNING_THRESHOLD_SEC) {
+ if (timeLeft < timeoutConfig.WARNING_THRESHOLD_SEC) {
return "text-red-500 font-bold animate-pulse";
}
return "text-accent";
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx
index 32a3dfc9e..01fe65f30 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/rendermessage.tsx
@@ -1,5 +1,5 @@
-import React from "react";
-import { User, Bot, DraftingCompass, Bug } from "lucide-react";
+import React, { useState } from "react";
+import { User, Bot, DraftingCompass, Bug, ChevronDown } from "lucide-react";
import {
AgentMessageConfig,
FunctionCall,
@@ -28,68 +28,182 @@ const getImageSource = (item: ImageContent): string => {
const RenderMultiModal: React.FC<{
content: (string | ImageContent)[];
thumbnail?: boolean;
-}> = ({ content, thumbnail = false }) => (
- <div className="space-y-2">
- {content.map((item, index) =>
- typeof item === "string" ? (
- <TruncatableText key={index} content={item} className="break-all" />
- ) : (
- <ClickableImage
- key={index}
- src={getImageSource(item)}
- alt={item.alt || "Image"}
- className={` h-auto rounded border border-secondary ${
- thumbnail ? "w-24 h-24 " : " w-full "
- }`}
- />
- )
- )}
- </div>
-);
-const RenderToolCall: React.FC<{ content: FunctionCall[] }> = ({ content }) => (
- <div className="space-y-2">
- {content.map((call) => (
- <div
- key={call.id}
- className="relative pl-3 border border-secondary rounded p-2"
- >
- <div className="absolute top-0 -left-0.5 w-1 bg-secondary h-full rounded"></div>
- <div className="font-medium">
- <DraftingCompass className="w-4 h-4 text-accent inline-block mr-1.5 -mt-0.5" />{" "}
- Calling {call.name} tool with arguments
- </div>
- <TruncatableText
- content={JSON.stringify(call.arguments, null, 2)}
- isJson={true}
- className="text-sm mt-1 bg-secondary p-2 rounded"
- />
+}> = ({ content, thumbnail = false }) => {
+ // Separate text and images
+ const texts = content.filter((item) => typeof item === "string") as string[];
+ const images = content.filter(
+ (item) => typeof item === "object" && item !== null
+ ) as ImageContent[];
+
+ // Use the larger of the two for navigation
+ const maxLen = Math.max(texts.length, images.length);
+ const [current, setCurrent] = useState(0);
+
+ const showPrev = () => setCurrent((c) => Math.max(0, c - 1));
+ const showNext = () => setCurrent((c) => Math.min(maxLen - 1, c + 1));
+
+ const currentText = texts[current] ?? texts[0] ?? "";
+ const currentImage = images[current] ?? images[0];
+
+ return (
+ <div className="flex gap-4 items-stretch relative">
+ {/* Text on the left, aligned to top */}
+ <div className="flex-1 min-w-0 flex items-start">
+ {currentText && (
+ <TruncatableText
+ content={currentText.slice(0, 500)}
+ className="break-all"
+ />
+ )}
</div>
- ))}
- </div>
-);
+ {/* Image on the right */}
+ <div className="flex-1 flex justify-center items-center relative">
+ {currentImage && (
+ <ClickableImage
+ src={getImageSource(currentImage)}
+ alt={currentImage.alt || "Image"}
+ className={`rounded border border-secondary max-h-96 w-auto max-w-full object-contain ${
+ thumbnail ? "w-24 h-24" : ""
+ }`}
+ />
+ )}
+ {/* Navigation buttons */}
+ {maxLen > 1 && (
+ <div className="absolute bottom-2 right-2 flex gap-2 z-10">
+ <button
+ onClick={showPrev}
+ disabled={current === 0}
+ className="bg-white/80 hover:bg-white text-black rounded-full px-2 py-1 shadow"
+ aria-label="Previous"
+ >
+ ◀
+ </button>
+ <button
+ onClick={showNext}
+ disabled={current >= maxLen - 1}
+ className="bg-white/80 hover:bg-white text-black rounded-full px-2 py-1 shadow"
+ aria-label="Next"
+ >
+ ▶
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+const RenderToolCall: React.FC<{ content: FunctionCall[] }> = ({ content }) => {
+ const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set());
+
+ const toggleExpansion = (callId: string) => {
+ setExpandedItems((prev) => {
+ const newSet = new Set(prev);
+ if (newSet.has(callId)) {
+ newSet.delete(callId);
+ } else {
+ newSet.add(callId);
+ }
+ return newSet;
+ });
+ };
+
+ return (
+ <div className="space-y-1">
+ {content.map((call) => {
+ const isExpanded = expandedItems.has(call.id);
+ return (
+ <div
+ key={call.id}
+ className="border mt-1 border-secondary bg-secondary rounded hover:bg-tertiary transition-colors"
+ >
+ <button
+ onClick={() => toggleExpansion(call.id)}
+ className="w-full flex items-center gap-2 p-2 text-left hover:bg-secondary/50 transition-colors"
+ >
+ <DraftingCompass className="w-4 h-4 text-accent flex-shrink-0" />
+ <span className="font-base text-sm">
+ Calling {call.name} tool
+ </span>
+ <div
+ className={`ml-auto transition-transform duration-200 ${
+ isExpanded ? "rotate-180" : "rotate-0"
+ }`}
+ >
+ <ChevronDown className="w-4 h-4" />
+ </div>
+ </button>
+ {isExpanded && (
+ <div className="border-t border-secondary p-2">
+ <TruncatableText
+ content={JSON.stringify(call.arguments, null, 2)}
+ isJson={true}
+ className="text-sm bg-secondary p-2 rounded"
+ />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+};
const RenderToolResult: React.FC<{ content: FunctionExecutionResult[] }> = ({
content,
-}) => (
- <div className="space-y-2">
- {content.map((result) => (
- <div
- key={result.call_id}
- className="rounded p-2 pl-3 relative border border-secondary"
- >
- <div className="absolute top-0 -left-0.5 w-1 bg-secondary h-full rounded"></div>
- <div className="font-medium">
- <DraftingCompass className="w-4 text-accent h-4 inline-block mr-1.5 -mt-0.5" />{" "}
- Tool Result
- </div>
- <TruncatableText
- content={result.content}
- className="text-sm mt-1 bg-secondary p-2 border border-secondary rounded scroll overflow-x-scroll"
- />
- </div>
- ))}
- </div>
-);
+}) => {
+ const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set());
+
+ const toggleExpansion = (callId: string) => {
+ setExpandedItems((prev) => {
+ const newSet = new Set(prev);
+ if (newSet.has(callId)) {
+ newSet.delete(callId);
+ } else {
+ newSet.add(callId);
+ }
+ return newSet;
+ });
+ };
+
+ return (
+ <div className="space-y-1">
+ {content.map((result) => {
+ const isExpanded = expandedItems.has(result.call_id);
+ return (
+ <div
+ key={result.call_id}
+ className="border mt-1 border-secondary bg-secondary rounded hover:bg-tertiary transition-colors"
+ >
+ <button
+ onClick={() => toggleExpansion(result.call_id)}
+ className="w-full flex items-center gap-2 p-2 text-left hover:bg-secondary/50 transition-colors"
+ >
+ <DraftingCompass className="w-4 h-4 text-accent flex-shrink-0" />
+ <span className="font-medium text-sm">
+ Tool result (ID: {result.call_id.slice(-8)})
+ </span>
+ <div
+ className={`ml-auto transition-transform duration-200 ${
+ isExpanded ? "rotate-180" : "rotate-0"
+ }`}
+ >
+ <ChevronDown className="w-4 h-4" />
+ </div>
+ </button>
+ {isExpanded && (
+ <div className="border-t border-secondary p-2">
+ <TruncatableText
+ content={result.content}
+ className="text-sm bg-secondary p-2 border border-secondary rounded scroll overflow-x-scroll"
+ />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+};
export const messageUtils = {
isToolCallContent(content: unknown): content is FunctionCall[] {
@@ -237,17 +351,24 @@ export const RenderMessage: React.FC<MessageProps> = ({
</div>
<div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-sm font-semibold text-primary">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-sm font-semibold text-primary truncate flex-1 min-w-0">
{message.source}
</span>
+ {message.models_usage && (
+ <span className="text-xs text-secondary flex-shrink-0">
+ Tokens:{" "}
+ {(message.models_usage.prompt_tokens || 0) +
+ (message.models_usage.completion_tokens || 0)}
+ </span>
+ )}
</div>
<div className="text-sm text-secondary">
{messageUtils.isToolCallContent(content) ? (
<RenderToolCall content={content} />
) : messageUtils.isMultiModalContent(content) ? (
- <RenderMultiModal content={content} thumbnail />
+ <RenderMultiModal content={content} thumbnail={false} />
) : messageUtils.isNestedMessageContent(content) ? (
<RenderNestedMessages content={content} />
) : messageUtils.isFunctionExecutionResult(content) ? (
@@ -261,13 +382,6 @@ export const RenderMessage: React.FC<MessageProps> = ({
/>
)}
</div>
- {message.models_usage && (
- <div className="text-xs text-secondary mt-1">
- Tokens:{" "}
- {(message.models_usage.prompt_tokens || 0) +
- (message.models_usage.completion_tokens || 0)}
- </div>
- )}
</div>
</div>
</div>
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/runview.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/runview.tsx
index 44b24f851..faa9f020f 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/runview.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/runview.tsx
@@ -11,12 +11,15 @@ import {
Bot,
PanelRightClose,
PanelRightOpen,
+ Play,
+ Pause,
+ RotateCcw,
} from "lucide-react";
import { Run, Message, TeamConfig, Component } from "../../../types/datamodel";
import AgentFlow from "./agentflow/agentflow";
import { RenderMessage } from "./rendermessage";
import InputRequestView from "./inputrequest";
-import { Tooltip } from "antd";
+import { Tooltip, Dropdown, MenuProps } from "antd";
import { getRelativeTimeString, LoadingDots } from "../../atoms";
import { useSettingsStore } from "../../settings/store";
@@ -106,12 +109,126 @@ const RunView: React.FC<RunViewProps> = ({
uiSettings.show_agent_flow_by_default ?? true
);
+ // Replay state
+ const [isReplaying, setIsReplaying] = useState(false);
+ const [replayMessageIndex, setReplayMessageIndex] = useState(0);
+ const [originalRun, setOriginalRun] = useState<Run | null>(null);
+ const replayIntervalRef = useRef<NodeJS.Timeout | null>(null);
+ const [replaySpeed, setReplaySpeed] = useState(1); // 1x speed by default
+
+ // Create a run object for display (either original or replaying version)
+ const displayRun = useMemo(() => {
+ if (!isReplaying || !originalRun) return run;
+
+ return {
+ ...originalRun,
+ messages: originalRun.messages.slice(0, replayMessageIndex + 1),
+ status:
+ replayMessageIndex < originalRun.messages.length - 1
+ ? ("active" as const)
+ : originalRun.status,
+ };
+ }, [run, isReplaying, originalRun, replayMessageIndex]);
+
const visibleMessages = useMemo(() => {
if (uiSettings.show_llm_call_events) {
- return run.messages;
+ return displayRun.messages;
+ }
+ return displayRun.messages.filter(
+ (msg) => msg.config.source !== "llm_call_event"
+ );
+ }, [displayRun.messages, uiSettings.show_llm_call_events]);
+
+ // Replay functions
+ const startReplay = () => {
+ if (
+ run.status !== "complete" &&
+ run.status !== "error" &&
+ run.status !== "stopped"
+ )
+ return;
+
+ setOriginalRun(run);
+ setReplayMessageIndex(0);
+ setIsReplaying(true);
+ setIsExpanded(true); // Ensure the messages are visible
+
+ // Start the replay interval with current speed
+ const intervalTime = 800 / replaySpeed; // Base time 800ms divided by speed multiplier
+ replayIntervalRef.current = setInterval(() => {
+ setReplayMessageIndex((prev) => {
+ if (prev >= run.messages.length - 1) {
+ setIsReplaying(false);
+ if (replayIntervalRef.current) {
+ clearInterval(replayIntervalRef.current);
+ replayIntervalRef.current = null;
+ }
+ return prev;
+ }
+ return prev + 1;
+ });
+ }, intervalTime);
+ };
+
+ const pauseReplay = () => {
+ if (replayIntervalRef.current) {
+ clearInterval(replayIntervalRef.current);
+ replayIntervalRef.current = null;
}
- return run.messages.filter((msg) => msg.config.source !== "llm_call_event");
- }, [run.messages, uiSettings.show_llm_call_events]);
+ setIsReplaying(false);
+ };
+
+ const resetReplay = () => {
+ if (replayIntervalRef.current) {
+ clearInterval(replayIntervalRef.current);
+ replayIntervalRef.current = null;
+ }
+ setIsReplaying(false);
+ setReplayMessageIndex(0);
+ setOriginalRun(null);
+ };
+
+ const changeReplaySpeed = (newSpeed: number) => {
+ setReplaySpeed(newSpeed);
+
+ // If currently replaying, restart with new speed
+ if (isReplaying && replayIntervalRef.current) {
+ clearInterval(replayIntervalRef.current);
+ const intervalTime = 800 / newSpeed;
+ replayIntervalRef.current = setInterval(() => {
+ setReplayMessageIndex((prev) => {
+ if (
+ prev >=
+ (originalRun?.messages.length || run.messages.length) - 1
+ ) {
+ setIsReplaying(false);
+ if (replayIntervalRef.current) {
+ clearInterval(replayIntervalRef.current);
+ replayIntervalRef.current = null;
+ }
+ return prev;
+ }
+ return prev + 1;
+ });
+ }, intervalTime);
+ }
+ };
+
+ // Cleanup interval on unmount
+ useEffect(() => {
+ return () => {
+ if (replayIntervalRef.current) {
+ clearInterval(replayIntervalRef.current);
+ }
+ };
+ }, []);
+
+ // Determine if replay is available
+ const canReplay =
+ (run.status === "complete" ||
+ run.status === "error" ||
+ run.status === "stopped") &&
+ run.messages.length > 0;
console.log("Run task", run.task);
@@ -125,7 +242,7 @@ const RunView: React.FC<RunViewProps> = ({
});
}
}, 450);
- }, [run.messages, streamingContent]);
+ }, [displayRun.messages, streamingContent]);
const calculateThreadTokens = (messages: Message[]) => {
// console.log("messages", messages);
return messages.reduce((total, msg) => {
@@ -139,6 +256,17 @@ const RunView: React.FC<RunViewProps> = ({
};
const getStatusIcon = (status: Run["status"]) => {
+ // If we're replaying, show replay status instead
+ if (isReplaying && originalRun) {
+ return (
+ <div className="inline-block mr-1">
+ <Play size={20} className="inline-block mr-1 text-accent" />
+ <span className="inline-block mr-2 ml-1">Replaying</span>
+ <LoadingDots size={8} />
+ </div>
+ );
+ }
+
switch (status) {
case "active":
return (
@@ -191,7 +319,8 @@ const RunView: React.FC<RunViewProps> = ({
}
};
- const lastResultMessage = run.team_result?.task_result?.messages.slice(-1)[0];
+ const lastResultMessage =
+ displayRun.team_result?.task_result?.messages.slice(-1)[0];
const lastMessage = getLastMeaningfulMessage(visibleMessages);
return (
@@ -202,28 +331,159 @@ const RunView: React.FC<RunViewProps> = ({
isFirstRun ? "mb-2" : "mt-4"
} mb-4 pb-2 pt-2 border-b border-dashed border-secondary`}
>
- <div className="text-xs text-secondary">
- <Tooltip
- title={
- <div className="text-xs">
- <div>ID: {run.id}</div>
- <div>Created: {new Date(run.created_at).toLocaleString()}</div>
- <div>Status: {run.status}</div>
- </div>
- }
- >
- <span className="cursor-help">
- Run ...{run.id} | {getRelativeTimeString(run?.created_at || "")}{" "}
- </span>
- </Tooltip>
- {!isFirstRun && (
- <>
- {" "}
- |{" "}
- <TriangleAlertIcon className="w-4 h-4 -mt-1 inline-block mr-1 ml-1" />
- Note: Each run does not share data with previous runs in the same
- session yet.
- </>
+ <div id="run-header" className="flex items-center justify-between">
+ <div className="text-xs text-secondary">
+ <Tooltip
+ title={
+ <div className="text-xs">
+ <div>ID: {run.id}</div>
+ <div>
+ Created: {new Date(run.created_at).toLocaleString()}
+ </div>
+ <div>Status: {run.status}</div>
+ </div>
+ }
+ >
+ <span className="cursor-help">
+ Run ...{run.id} | {getRelativeTimeString(run?.created_at || "")}{" "}
+ </span>
+ </Tooltip>
+ {!isFirstRun && (
+ <>
+ {" "}
+ |{" "}
+ <TriangleAlertIcon className="w-4 h-4 -mt-1 inline-block mr-1 ml-1" />
+ Note: Each run does not share data with previous runs in the
+ same session yet.
+ </>
+ )}
+ </div>
+
+ {/* Replay Controls */}
+ {canReplay && (
+ <div className="flex items-center gap-2">
+ {!isReplaying && !originalRun && (
+ <div className="flex items-center gap-0">
+ <button
+ onClick={startReplay}
+ className="p-1 px-2 rounded-l hover:bg-secondary transition-colors text-secondary hover:text-primary"
+ >
+ <Play className="inline-block" size={16} />
+ <span className="inline-block text-xs text-secondary ml-1">
+ Replay Run ({replaySpeed}x)
+ </span>
+ </button>
+ <Dropdown
+ menu={{
+ items: [
+ {
+ key: "0.1",
+ label: "0.1x",
+ onClick: () => changeReplaySpeed(0.1),
+ },
+ {
+ key: "0.5",
+ label: "0.5x",
+ onClick: () => changeReplaySpeed(0.5),
+ },
+ {
+ key: "1",
+ label: "1x",
+ onClick: () => changeReplaySpeed(1),
+ },
+ {
+ key: "2",
+ label: "2x",
+ onClick: () => changeReplaySpeed(2),
+ },
+ {
+ key: "5",
+ label: "5x",
+ onClick: () => changeReplaySpeed(5),
+ },
+ ],
+ selectedKeys: [replaySpeed.toString()],
+ }}
+ trigger={["click"]}
+ >
+ <button className="p-1 px-1 rounded-r hover:bg-secondary transition-colors text-secondary hover:text-primary border-l border-secondary">
+ <ChevronDown className="inline-block" size={12} />
+ </button>
+ </Dropdown>
+ </div>
+ )}
+
+ {isReplaying && (
+ <div className="flex items-center gap-0">
+ <button
+ onClick={pauseReplay}
+ className="p-1 px-2 rounded-l hover:bg-secondary transition-colors text-accent hover:text-primary"
+ >
+ <Pause className="inline-block" size={16} />
+ <span className="inline-block text-xs text-accent ml-1">
+ Pause Replay ({replaySpeed}x)
+ </span>
+ </button>
+
+ <Dropdown
+ menu={{
+ items: [
+ {
+ key: "0.1",
+ label: "0.1x",
+ onClick: () => changeReplaySpeed(0.1),
+ },
+ {
+ key: "0.5",
+ label: "0.5x",
+ onClick: () => changeReplaySpeed(0.5),
+ },
+ {
+ key: "1",
+ label: "1x",
+ onClick: () => changeReplaySpeed(1),
+ },
+ {
+ key: "2",
+ label: "2x",
+ onClick: () => changeReplaySpeed(2),
+ },
+ {
+ key: "5",
+ label: "5x",
+ onClick: () => changeReplaySpeed(5),
+ },
+ ],
+ selectedKeys: [replaySpeed.toString()],
+ }}
+ trigger={["click"]}
+ >
+ <button className="p-1 px-1 rounded-r hover:bg-secondary transition-colors text-secondary hover:text-primary border-l border-secondary">
+ <ChevronDown className="inline-block" size={12} />
+ </button>
+ </Dropdown>
+ </div>
+ )}
+
+ {(isReplaying || originalRun) && (
+ <button
+ onClick={resetReplay}
+ className="p-1 px-2 rounded hover:bg-secondary transition-colors text-secondary hover:text-primary"
+ >
+ <RotateCcw className="inline-block" size={16} />{" "}
+ <span className="inline-block text-xs text-secondary">
+ Reset Replay
+ </span>
+ </button>
+ )}
+
+ {(isReplaying || originalRun) && (
+ <div className="text-xs text-secondary">
+ {replayMessageIndex + 1}/
+ {originalRun?.messages.length || run.messages.length}
+ </div>
+ )}
+ </div>
)}
</div>
</div>
@@ -231,7 +491,7 @@ const RunView: React.FC<RunViewProps> = ({
{/* User Message */}
<div className="flex flex-col items-end w-full">
<div className="w-full">
- <RenderMessage message={run.task} isLast={false} />
+ <RenderMessage message={displayRun.task} isLast={false} />
</div>
</div>
@@ -248,10 +508,12 @@ const RunView: React.FC<RunViewProps> = ({
{/* Main Response Container */}
<div className="p-4 bg-secondary border border-secondary rounded">
<div className="flex justify-between items-start mb-2">
- <div className="text-primary">{getStatusIcon(run.status)}</div>
+ <div className="text-primary">
+ {getStatusIcon(displayRun.status)}
+ </div>
{/* Cancel Button - More prominent placement */}
- {isActive && onCancel && (
+ {isActive && onCancel && !isReplaying && (
<button
onClick={onCancel}
className="px-4 text-sm py-2 bg-red-500 hover:bg-red-600 text-white rounded-md transition-colors flex items-center gap-2"
@@ -263,23 +525,25 @@ const RunView: React.FC<RunViewProps> = ({
</div>
{/* Final Response */}
- {run.status !== "awaiting_input" && run.status !== "active" && (
- <div className="text-sm break-all">
- <div className="text-xs bg-tertiary mb-1 text-secondary border-secondary -mt-2 bdorder rounded p-2">
- Stop reason: {run.team_result?.task_result?.stop_reason}
- </div>
+ {displayRun.status !== "awaiting_input" &&
+ displayRun.status !== "active" && (
+ <div className="text-sm break-all">
+ <div className="text-xs bg-tertiary mb-1 text-secondary border-secondary -mt-2 bdorder rounded p-2">
+ Stop reason:{" "}
+ {displayRun.team_result?.task_result?.stop_reason}
+ </div>
- {lastMessage ? (
- <RenderMessage message={lastMessage.config} isLast={true} />
- ) : (
- <>
- {lastResultMessage && (
- <RenderMessage message={lastResultMessage} />
- )}
- </>
- )}
- </div>
- )}
+ {lastMessage ? (
+ <RenderMessage message={lastMessage.config} isLast={true} />
+ ) : (
+ <>
+ {lastResultMessage && (
+ <RenderMessage message={lastResultMessage} />
+ )}
+ </>
+ )}
+ </div>
+ )}
</div>
{/* Thread Section */}
@@ -358,7 +622,8 @@ const RunView: React.FC<RunViewProps> = ({
</div>
))}
{streamingContent &&
- streamingContent.runId === run.id && (
+ streamingContent.runId === run.id &&
+ !isReplaying && (
<div className="mr-2 mb-10">
<StreamingMessage
content={streamingContent.content}
@@ -368,18 +633,20 @@ const RunView: React.FC<RunViewProps> = ({
)}
{/* Input Request UI */}
- {run.status === "awaiting_input" && onInputResponse && (
- <div className="mt-4 mr-2">
- <InputRequestView
- prompt="Type your response..."
- onSubmit={onInputResponse}
- />
- </div>
- )}
+ {displayRun.status === "awaiting_input" &&
+ onInputResponse &&
+ !isReplaying && (
+ <div className="mt-4 mr-2">
+ <InputRequestView
+ prompt="Type your response..."
+ onSubmit={onInputResponse}
+ />
+ </div>
+ )}
<div className="text-primary mt-2">
<div className="w-4 h-4 inline-block border-secondary rounded-bl-lg border-l-2 border-b-2"></div>{" "}
<div className="inline-block ">
- {getStatusIcon(run.status)}
+ {getStatusIcon(displayRun.status)}
</div>
</div>
</div>
@@ -401,7 +668,7 @@ const RunView: React.FC<RunViewProps> = ({
<AgentFlow
teamConfig={teamConfig}
run={{
- ...run,
+ ...displayRun,
messages: getAgentMessages(visibleMessages),
}}
/>
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/types.ts b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/types.ts
index fa169da73..9fbab4ea4 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/chat/types.ts
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/chat/types.ts
@@ -2,13 +2,13 @@ import {
AgentMessageConfig,
Message,
TaskResult,
- ThreadStatus,
+ RunStatus,
} from "../../../types/datamodel";
export interface ThreadState {
messages: AgentMessageConfig[];
finalResult?: any;
- status: ThreadStatus;
+ status: RunStatus;
isExpanded: boolean;
reason?: string;
inputRequest?: {
@@ -32,13 +32,19 @@ export interface ModelUsage {
completion_tokens: number;
}
-export const TIMEOUT_CONFIG = {
- DURATION_MS: 3 * 60 * 1000, // 3 minutes in milliseconds
- DURATION_SEC: 3 * 60, // 3 minutes in seconds
+// Create timeout configuration based on user settings
+export const createTimeoutConfig = (timeoutMinutes: number = 3) => ({
+ DURATION_MS: timeoutMinutes * 60 * 1000, // timeout in milliseconds
+ DURATION_SEC: timeoutMinutes * 60, // timeout in seconds
WEBSOCKET_CODE: 4000, // WebSocket close code for timeout
- DEFAULT_MESSAGE: "Input timeout after 3 minutes",
+ DEFAULT_MESSAGE: `Input timeout after ${timeoutMinutes} minute${
+ timeoutMinutes !== 1 ? "s" : ""
+ }`,
WARNING_THRESHOLD_SEC: 30, // Show warning when 30 seconds remaining
-} as const;
+});
+
+// Default timeout config for backward compatibility
+export const TIMEOUT_CONFIG = createTimeoutConfig(3);
export interface TimeoutError {
code: typeof TIMEOUT_CONFIG.WEBSOCKET_CODE;
diff --git a/python/packages/autogen-studio/frontend/src/components/views/playground/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/playground/manager.tsx
index b2643b54e..fcc026483 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/playground/manager.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/playground/manager.tsx
@@ -273,7 +273,7 @@ export const SessionManager: React.FC = () => {
}`}
>
{session && sessions.length > 0 ? (
- <div className="pl-4 flex gap-4">
+ <div className="flex gap-4 pl-4">
{/* Primary ChatView */}
<div className={`flex-1 ${isCompareMode ? "w-1/2" : "w-full"}`}>
<ChatView
@@ -301,7 +301,7 @@ export const SessionManager: React.FC = () => {
</div>
) : (
<div className="flex items-center justify-center h-full text-secondary">
- No session selected. Create or select a session from the sidebar.
+ "No session selected. Create or select a session from the sidebar."
</div>
)}
</div>
diff --git a/python/packages/autogen-studio/frontend/src/components/views/settings/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/settings/manager.tsx
index 37312d521..679492346 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/settings/manager.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/settings/manager.tsx
@@ -71,42 +71,42 @@ export const SettingsManager: React.FC = () => {
),
children: <UISettingsPanel userId={userId} />,
},
- {
- key: "model",
- label: (
- <span className="flex items-center gap-2">
- <Brain className="w-4 h-4" />
- Default Model
- </span>
- ),
- children: (
- <div className="mt-4">
- <ModelConfigPanel
- modelComponent={modelComponent}
- onModelUpdate={async () => {}}
- />
- </div>
- ),
- },
- {
- key: "environment",
- label: (
- <span className="flex items-center gap-2">
- <Variable className="w-4 h-4" />
- Environment Variables
- </span>
- ),
- children: (
- <div className="mt-4">
- <EnvironmentVariablesPanel
- serverSettings={serverSettings}
- loading={false}
- userId={userId}
- initializeSettings={initializeSettings}
- />
- </div>
- ),
- },
+ // {
+ // key: "model",
+ // label: (
+ // <span className="flex items-center gap-2">
+ // <Brain className="w-4 h-4" />
+ // Default Model
+ // </span>
+ // ),
+ // children: (
+ // <div className="mt-4">
+ // <ModelConfigPanel
+ // modelComponent={modelComponent}
+ // onModelUpdate={async () => {}}
+ // />
+ // </div>
+ // ),
+ // },
+ // {
+ // key: "environment",
+ // label: (
+ // <span className="flex items-center gap-2">
+ // <Variable className="w-4 h-4" />
+ // Environment Variables
+ // </span>
+ // ),
+ // children: (
+ // <div className="mt-4">
+ // <EnvironmentVariablesPanel
+ // serverSettings={serverSettings}
+ // loading={false}
+ // userId={userId}
+ // initializeSettings={initializeSettings}
+ // />
+ // </div>
+ // ),
+ // },
];
return (
diff --git a/python/packages/autogen-studio/frontend/src/components/views/settings/store.tsx b/python/packages/autogen-studio/frontend/src/components/views/settings/store.tsx
index 201f185de..e73a47934 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/settings/store.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/settings/store.tsx
@@ -9,6 +9,7 @@ const DEFAULT_UI_SETTINGS: UISettings = {
show_llm_call_events: false,
expanded_messages_by_default: false,
show_agent_flow_by_default: false,
+ human_input_timeout_minutes: 3,
};
interface SettingsState {
diff --git a/python/packages/autogen-studio/frontend/src/components/views/settings/view/ui.tsx b/python/packages/autogen-studio/frontend/src/components/views/settings/view/ui.tsx
index 896a622be..4608f1b84 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/settings/view/ui.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/settings/view/ui.tsx
@@ -13,6 +13,17 @@ interface SettingToggleProps {
disabled?: boolean;
}
+interface SettingNumberInputProps {
+ value: number;
+ onChange: (value: number) => void;
+ label: string;
+ description?: string;
+ disabled?: boolean;
+ min?: number;
+ max?: number;
+ suffix?: string;
+}
+
const SettingToggle: React.FC<SettingToggleProps> = ({
checked,
onChange,
@@ -52,6 +63,43 @@ const SettingToggle: React.FC<SettingToggleProps> = ({
</div>
);
+const SettingNumberInput: React.FC<SettingNumberInputProps> = ({
+ value,
+ onChange,
+ label,
+ description,
+ disabled = false,
+ min = 1,
+ max = 30,
+ suffix = "",
+}) => (
+ <div className="flex justify-between items-start p-4 hover:bg-secondary rounded transition-colors">
+ <div className="flex flex-col gap-1">
+ <label className="font-medium">{label}</label>
+ {description && (
+ <span className="text-sm text-secondary">{description}</span>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ <input
+ type="number"
+ value={value}
+ onChange={(e) => {
+ const newValue = parseInt(e.target.value);
+ if (!isNaN(newValue) && newValue >= min && newValue <= max) {
+ onChange(newValue);
+ }
+ }}
+ disabled={disabled}
+ min={min}
+ max={max}
+ className="w-16 px-2 py-1 text-sm border border-secondary rounded focus:border-accent focus:ring-1 focus:ring-accent outline-none disabled:opacity-50 bg-primary"
+ />
+ {suffix && <span className="text-sm text-secondary">{suffix}</span>}
+ </div>
+ </div>
+);
+
interface UISettingsPanelProps {
userId: string;
}
@@ -68,6 +116,7 @@ export const UISettingsPanel: React.FC<UISettingsPanelProps> = ({ userId }) => {
show_llm_call_events: false,
expanded_messages_by_default: false,
show_agent_flow_by_default: false,
+ human_input_timeout_minutes: 3,
});
const [isDirty, setIsDirty] = useState(false);
@@ -80,7 +129,10 @@ export const UISettingsPanel: React.FC<UISettingsPanelProps> = ({ userId }) => {
}, [storeUISettings]);
// Update local state when a setting is changed
- const handleSettingChange = (key: keyof UISettings, value: boolean) => {
+ const handleSettingChange = (
+ key: keyof UISettings,
+ value: boolean | number
+ ) => {
setLocalUISettings((prev) => ({
...prev,
[key]: value,
@@ -104,6 +156,7 @@ export const UISettingsPanel: React.FC<UISettingsPanelProps> = ({ userId }) => {
show_llm_call_events: false,
expanded_messages_by_default: false,
show_agent_flow_by_default: false,
+ human_input_timeout_minutes: 3,
};
// Update local state
@@ -242,6 +295,19 @@ export const UISettingsPanel: React.FC<UISettingsPanelProps> = ({ userId }) => {
description="Display the agent flow diagram automatically"
disabled={isSaving}
/>
+
+ <SettingNumberInput
+ value={localUISettings.human_input_timeout_minutes ?? 3}
+ onChange={(value) =>
+ handleSettingChange("human_input_timeout_minutes", value)
+ }
+ label="Human Input Timeout"
+ description="How long to wait for user input before timing out (1-30 minutes)"
+ disabled={isSaving}
+ min={1}
+ max={30}
+ suffix="minutes"
+ />
</div>
<div className="mt-4 hidden text-xs text-secondary">
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/api.ts b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/api.ts
index 3076e4859..1c2b43782 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/api.ts
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/api.ts
@@ -1,6 +1,5 @@
import { Team, Component, ComponentConfig } from "../../types/datamodel";
import { BaseAPI } from "../../utils/baseapi";
-import { getServerUrl } from "../../utils/utils";
interface ValidationError {
field: string;
@@ -119,6 +118,5 @@ export class ValidationAPI extends BaseAPI {
}
}
-export const validationAPI = new ValidationAPI();
-
export const teamAPI = new TeamAPI();
+export const validationAPI = new ValidationAPI();
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/builder.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/builder.tsx
index 827579a18..b153552b0 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/builder.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/builder.tsx
@@ -101,6 +101,7 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({
updateNode,
selectedNodeId,
setSelectedNode,
+ setNodeUserPositioned,
} = useTeamBuilderStore();
const currentHistoryIndex = useTeamBuilderStore(
@@ -150,7 +151,9 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({
React.useEffect(() => {
if (team?.component) {
const { nodes: initialNodes, edges: initialEdges } = loadFromJson(
- team.component
+ team.component,
+ true,
+ team.id?.toString()
);
setNodes(initialNodes);
setEdges(initialEdges);
@@ -169,14 +172,14 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({
try {
const config = JSON.parse(value);
// Always consider JSON edits as changes that should affect isDirty state
- loadFromJson(config, false);
+ loadFromJson(config, false, team?.id?.toString());
// Force history update even if nodes/edges appear same
useTeamBuilderStore.getState().addToHistory();
} catch (error) {
console.error("Invalid JSON:", error);
}
}, 1000),
- [loadFromJson]
+ [loadFromJson, team?.id]
);
// Cleanup debounced function
@@ -272,6 +275,7 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({
agent: ["team"],
team: [],
termination: ["team"],
+ workbench: ["agent"],
};
return validTargets[draggedType]?.includes(targetType) || false;
};
@@ -495,6 +499,11 @@ export const TeamBuilder: React.FC<TeamBuilderProps> = ({
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
+ onNodeDragStop={(_, node) => {
+ // Mark node as user-positioned when dragged
+ setNodeUserPositioned(node.id, node.position);
+ console.log("Node dragged:", node.id);
+ }}
// onNodeClick={(_, node) => setSelectedNode(node.id)}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/component-editor.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/component-editor.tsx
index aa4a50a1f..69723d0c4 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/component-editor.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/component-editor.tsx
@@ -1,23 +1,45 @@
import React, { useState, useCallback, useRef } from "react";
import { Button, Breadcrumb, message, Tooltip } from "antd";
import { ChevronLeft, Code, FormInput, PlayCircle } from "lucide-react";
-import { Component, ComponentConfig } from "../../../../types/datamodel";
+import {
+ Component,
+ ComponentConfig,
+ AgentConfig,
+ AssistantAgentConfig,
+ StaticWorkbenchConfig,
+ WorkbenchConfig,
+} from "../../../../types/datamodel";
import {
isTeamComponent,
isAgentComponent,
isModelComponent,
isToolComponent,
+ isWorkbenchComponent,
isTerminationComponent,
+ isAssistantAgent,
+ isStaticWorkbench,
} from "../../../../types/guards";
import { AgentFields } from "./fields/agent-fields";
import { ModelFields } from "./fields/model-fields";
import { TeamFields } from "./fields/team-fields";
import { ToolFields } from "./fields/tool-fields";
+import { WorkbenchFields } from "./fields/workbench";
import { TerminationFields } from "./fields/termination-fields";
import debounce from "lodash.debounce";
import { MonacoEditor } from "../../../monaco";
import { ComponentTestResult, validationAPI } from "../../api";
import TestDetails from "./testresults";
+
+// Helper function to normalize workbench format (handle both single object and array)
+const normalizeWorkbenches = (
+ workbench:
+ | Component<WorkbenchConfig>[]
+ | Component<WorkbenchConfig>
+ | undefined
+): Component<WorkbenchConfig>[] => {
+ if (!workbench) return [];
+ return Array.isArray(workbench) ? workbench : [workbench];
+};
export interface EditPath {
componentType: string;
id: string;
@@ -65,13 +87,36 @@ export const ComponentEditor: React.FC<ComponentEditorProps> = ({
(current, path) => {
if (!current) return null;
- const field = current.config[
+ let field = current.config[
path.parentField as keyof typeof current.config
] as
| Component<ComponentConfig>[]
| Component<ComponentConfig>
| undefined;
+ // Special handling for workbench field normalization
+ if (path.parentField === "workbench" && field) {
+ field = normalizeWorkbenches(
+ field as Component<WorkbenchConfig>[] | Component<WorkbenchConfig>
+ );
+ }
+
+ // Special handling for tools within workbenches
+ if (path.parentField === "tools" && !field) {
+ // Check if tools are nested within a workbench for agents
+ if (isAgentComponent(current) && isAssistantAgent(current)) {
+ const agentConfig = current.config as AssistantAgentConfig;
+ const workbenches = normalizeWorkbenches(agentConfig.workbench);
+ const staticWorkbench = workbenches.find((wb) =>
+ isStaticWorkbench(wb)
+ );
+ if (staticWorkbench) {
+ field = (staticWorkbench.config as StaticWorkbenchConfig)
+ ?.tools;
+ }
+ }
+ }
+
if (Array.isArray(field)) {
// If index is provided, use it directly (preferred method)
if (
@@ -120,9 +165,32 @@ export const ComponentEditor: React.FC<ComponentEditorProps> = ({
}
const [currentPath, ...remainingPath] = path;
- const field =
+ let field: any =
root.config[currentPath.parentField as keyof typeof root.config];
+ // Special handling for workbench field normalization
+ if (currentPath.parentField === "workbench" && field) {
+ field = normalizeWorkbenches(
+ field as Component<WorkbenchConfig>[] | Component<WorkbenchConfig>
+ );
+ }
+
+ // Special handling for tools within workbenches
+ let isWorkbenchTools = false;
+ if (currentPath.parentField === "tools" && !field) {
+ if (isAgentComponent(root) && isAssistantAgent(root)) {
+ const agentConfig = root.config as AssistantAgentConfig;
+ const workbenches = normalizeWorkbenches(agentConfig.workbench);
+ const staticWorkbench = workbenches.find((wb) =>
+ isStaticWorkbench(wb)
+ );
+ if (staticWorkbench) {
+ field = (staticWorkbench.config as StaticWorkbenchConfig)?.tools;
+ isWorkbenchTools = true;
+ }
+ }
+ }
+
const updateField = (fieldValue: any): any => {
if (Array.isArray(fieldValue)) {
// If we have an index, use it directly for the update
@@ -167,7 +235,32 @@ export const ComponentEditor: React.FC<ComponentEditorProps> = ({
...root,
config: {
...root.config,
- [currentPath.parentField]: updateField(field),
+ ...(isWorkbenchTools &&
+ isAgentComponent(root) &&
+ isAssistantAgent(root)
+ ? (() => {
+ const agentConfig = root.config as AssistantAgentConfig;
+ const workbenches = normalizeWorkbenches(agentConfig.workbench);
+ const staticWorkbenchIndex = workbenches.findIndex((wb) =>
+ isStaticWorkbench(wb)
+ );
+
+ if (staticWorkbenchIndex !== -1) {
+ const updatedWorkbenches = [...workbenches];
+ updatedWorkbenches[staticWorkbenchIndex] = {
+ ...workbenches[staticWorkbenchIndex],
+ config: {
+ ...workbenches[staticWorkbenchIndex].config,
+ tools: updateField(field),
+ },
+ };
+ return { workbench: updatedWorkbenches };
+ }
+ return {};
+ })()
+ : {
+ [currentPath.parentField]: updateField(field),
+ }),
},
};
},
@@ -280,9 +373,14 @@ export const ComponentEditor: React.FC<ComponentEditorProps> = ({
/>
);
}
+ // NOTE: Individual tools are deprecated - tools are now managed within workbenches
+ // This is kept for backward compatibility during the transition
if (isToolComponent(currentComponent)) {
return <ToolFields {...commonProps} />;
}
+ if (isWorkbenchComponent(currentComponent)) {
+ return <WorkbenchFields {...commonProps} />;
+ }
if (isTerminationComponent(currentComponent)) {
return (
<TerminationFields
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/agent-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/agent-fields.tsx
index 429b60aa4..f66563059 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/agent-fields.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/agent-fields.tsx
@@ -1,25 +1,62 @@
-import React, { useCallback } from "react";
-import { Input, Switch, Button, Tooltip } from "antd";
-import { Edit, HelpCircle, Trash2, PlusCircle } from "lucide-react";
+import React, { useCallback, useState } from "react";
+import {
+ Input,
+ Switch,
+ Button,
+ Tooltip,
+ Collapse,
+ InputNumber,
+ Dropdown,
+} from "antd";
+import {
+ Edit,
+ HelpCircle,
+ Trash2,
+ PlusCircle,
+ ChevronDown,
+ Wrench,
+ User,
+ Settings,
+ Code,
+} from "lucide-react";
import {
Component,
ComponentConfig,
AgentConfig,
FunctionToolConfig,
+ StaticWorkbenchConfig,
+ WorkbenchConfig,
} from "../../../../../types/datamodel";
import {
isAssistantAgent,
isUserProxyAgent,
isWebSurferAgent,
+ isStaticWorkbench,
+ isMcpWorkbench,
} from "../../../../../types/guards";
-import DetailGroup from "../detailgroup";
const { TextArea } = Input;
+// Helper function to normalize workbench format (handle both single object and array)
+const normalizeWorkbenches = (
+ workbench:
+ | Component<WorkbenchConfig>[]
+ | Component<WorkbenchConfig>
+ | undefined
+): Component<WorkbenchConfig>[] => {
+ if (!workbench) return [];
+ return Array.isArray(workbench) ? workbench : [workbench];
+};
+
interface AgentFieldsProps {
component: Component<AgentConfig>;
onChange: (updates: Partial<Component<ComponentConfig>>) => void;
- onNavigate?: (componentType: string, id: string, parentField: string) => void;
+ onNavigate?: (
+ componentType: string,
+ id: string,
+ parentField: string,
+ index?: number
+ ) => void;
workingCopy?: Component<ComponentConfig> | null;
setWorkingCopy?: (component: Component<ComponentConfig> | null) => void;
editPath?: any[];
@@ -84,16 +121,6 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
[component, handleComponentUpdate]
);
- const handleRemoveTool = useCallback(
- (toolIndex: number) => {
- if (!isAssistantAgent(component)) return;
- const newTools = [...(component.config.tools || [])];
- newTools.splice(toolIndex, 1);
- handleConfigUpdate("tools", newTools);
- },
- [component, handleConfigUpdate]
- );
-
const handleAddTool = useCallback(() => {
if (!isAssistantAgent(component)) return;
@@ -113,12 +140,49 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
},
};
- // Update both working copy and actual component state
- const currentTools = component.config.tools || [];
+ // Get or create workbenches array
+ let workbenches = normalizeWorkbenches(component.config.workbench);
+
+ // Find existing StaticWorkbench or create one
+ let workbenchIndex = workbenches.findIndex((wb) => isStaticWorkbench(wb));
+
+ let workbench: Component<StaticWorkbenchConfig>;
+ if (workbenchIndex === -1) {
+ // Create a new StaticWorkbench
+ workbench = {
+ provider: "autogen_core.tools.StaticWorkbench",
+ component_type: "workbench",
+ config: {
+ tools: [],
+ },
+ label: "Static Workbench",
+ } as Component<StaticWorkbenchConfig>;
+ workbenches = [...workbenches, workbench];
+ workbenchIndex = workbenches.length - 1;
+ } else {
+ workbench = workbenches[
+ workbenchIndex
+ ] as Component<StaticWorkbenchConfig>;
+ }
+
+ const staticConfig = workbench.config as StaticWorkbenchConfig;
+ const currentTools = staticConfig.tools || [];
const updatedTools = [...currentTools, blankTool];
- // Update the actual component state
- handleConfigUpdate("tools", updatedTools);
+ // Update workbench config
+ const updatedWorkbench = {
+ ...workbench,
+ config: {
+ ...staticConfig,
+ tools: updatedTools,
+ },
+ };
+
+ // Update the workbenches array
+ const updatedWorkbenches = [...workbenches];
+ updatedWorkbenches[workbenchIndex] = updatedWorkbench;
+
+ handleConfigUpdate("workbench", updatedWorkbenches);
// If working copy functionality is available, update that too
if (
@@ -131,7 +195,7 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
const updatedCopy = updateComponentAtPath(workingCopy, editPath, {
config: {
...getCurrentComponent(workingCopy)?.config,
- tools: updatedTools,
+ workbench: updatedWorkbenches,
},
});
setWorkingCopy(updatedCopy);
@@ -146,379 +210,840 @@ export const AgentFields: React.FC<AgentFieldsProps> = ({
editPath,
]);
+ // Helper functions to add different types of workbenches
+ const addStaticWorkbench = useCallback(() => {
+ if (!isAssistantAgent(component)) return;
+
+ const existingWorkbenches = normalizeWorkbenches(
+ component.config.workbench
+ );
+ const staticWorkbenchCount = existingWorkbenches.filter((wb) =>
+ isStaticWorkbench(wb)
+ ).length;
+ const workbenchId = `static-workbench-${Date.now()}`; // Unique ID
+
+ const newWorkbench: Component<WorkbenchConfig> = {
+ provider: "autogen_core.tools.StaticWorkbench",
+ component_type: "workbench",
+ version: 1,
+ component_version: 1,
+ config: { tools: [] },
+ label:
+ staticWorkbenchCount > 0
+ ? `Static Workbench ${staticWorkbenchCount + 1}`
+ : "Static Workbench",
+ description: "A static workbench for managing custom tools",
+ };
+ const normalizedWorkbenches = normalizeWorkbenches(
+ component.config.workbench
+ );
+ handleConfigUpdate("workbench", [...normalizedWorkbenches, newWorkbench]);
+ }, [component, handleConfigUpdate]);
+
+ const addStdioMcpWorkbench = useCallback(() => {
+ if (!isAssistantAgent(component)) return;
+
+ const existingWorkbenches = normalizeWorkbenches(
+ component.config.workbench
+ );
+ const mcpWorkbenchCount = existingWorkbenches.filter((wb) =>
+ isMcpWorkbench(wb)
+ ).length;
+
+ const newMcpWorkbench: Component<WorkbenchConfig> = {
+ provider: "autogen_ext.tools.mcp.McpWorkbench",
+ component_type: "workbench",
+ version: 1,
+ component_version: 1,
+ config: {
+ server_params: {
+ type: "StdioServerParams",
+ command: "server-command",
+ args: [],
+ env: {},
+ },
+ },
+ label:
+ mcpWorkbenchCount > 0
+ ? `Stdio MCP Workbench ${mcpWorkbenchCount + 1}`
+ : "Stdio MCP Workbench",
+ description: "An MCP workbench that connects via stdio to local servers",
+ };
+ const normalizedWorkbenches = normalizeWorkbenches(
+ component.config.workbench
+ );
+ const updatedWorkbenches = [...normalizedWorkbenches, newMcpWorkbench];
+ handleConfigUpdate("workbench", updatedWorkbenches);
+
+ // Navigate to edit the newly created workbench if navigation is available
+ if (onNavigate) {
+ const workbenchIndex = updatedWorkbenches.length - 1; // New workbench is at the end
+ onNavigate(
+ "workbench",
+ newMcpWorkbench.label || "Stdio MCP Workbench",
+ "workbench",
+ workbenchIndex
+ );
+ }
+ }, [component, handleConfigUpdate, onNavigate]);
+
+ const addStreamableMcpWorkbench = useCallback(() => {
+ if (!isAssistantAgent(component)) return;
+
+ const existingWorkbenches = normalizeWorkbenches(
+ component.config.workbench
+ );
+ const mcpWorkbenchCount = existingWorkbenches.filter((wb) =>
+ isMcpWorkbench(wb)
+ ).length;
+
+ const newMcpWorkbench: Component<WorkbenchConfig> = {
+ provider: "autogen_ext.tools.mcp.McpWorkbench",
+ component_type: "workbench",
+ version: 1,
+ component_version: 1,
+ config: {
+ server_params: {
+ type: "StreamableHttpServerParams",
+ url: "https://example.com/mcp",
+ headers: {},
+ timeout: 30,
+ sse_read_timeout: 300,
+ terminate_on_close: true,
+ },
+ },
+ label:
+ mcpWorkbenchCount > 0
+ ? `Streamable MCP Workbench ${mcpWorkbenchCount + 1}`
+ : "Streamable MCP Workbench",
+ description:
+ "An MCP workbench that connects via HTTP streaming to remote servers",
+ };
+ const normalizedWorkbenches = normalizeWorkbenches(
+ component.config.workbench
+ );
+ const updatedWorkbenches = [...normalizedWorkbenches, newMcpWorkbench];
+ handleConfigUpdate("workbench", updatedWorkbenches);
+
+ // Navigate to edit the newly created workbench if navigation is available
+ if (onNavigate) {
+ const workbenchIndex = updatedWorkbenches.length - 1; // New workbench is at the end
+ onNavigate(
+ "workbench",
+ newMcpWorkbench.label || "Streamable MCP Workbench",
+ "workbench",
+ workbenchIndex
+ );
+ }
+ }, [component, handleConfigUpdate, onNavigate]);
+
+ const addSseMcpWorkbench = useCallback(() => {
+ if (!isAssistantAgent(component)) return;
+
+ const existingWorkbenches = normalizeWorkbenches(
+ component.config.workbench
+ );
+ const mcpWorkbenchCount = existingWorkbenches.filter((wb) =>
+ isMcpWorkbench(wb)
+ ).length;
+
+ const newMcpWorkbench: Component<WorkbenchConfig> = {
+ provider: "autogen_ext.tools.mcp.McpWorkbench",
+ component_type: "workbench",
+ version: 1,
+ component_version: 1,
+ config: {
+ server_params: {
+ type: "SseServerParams",
+ url: "https://example.com/mcp/sse",
+ headers: {},
+ timeout: 30,
+ sse_read_timeout: 300,
+ },
+ },
+ label:
+ mcpWorkbenchCount > 0
+ ? `SSE MCP Workbench ${mcpWorkbenchCount + 1}`
+ : "SSE MCP Workbench",
+ description:
+ "An MCP workbench that connects via Server-Sent Events to remote servers",
+ };
+ const normalizedWorkbenches = normalizeWorkbenches(
+ component.config.workbench
+ );
+ const updatedWorkbenches = [...normalizedWorkbenches, newMcpWorkbench];
+ handleConfigUpdate("workbench", updatedWorkbenches);
+
+ // Navigate to edit the newly created workbench if navigation is available
+ if (onNavigate) {
+ const workbenchIndex = updatedWorkbenches.length - 1; // New workbench is at the end
+ onNavigate(
+ "workbench",
+ newMcpWorkbench.label || "SSE MCP Workbench",
+ "workbench",
+ workbenchIndex
+ );
+ }
+ }, [component, handleConfigUpdate, onNavigate]);
+
+ const label = component.config.name || component.label || "Unnamed Agent";
+ const displayName =
+ label.length > 20 ? `${label.substring(0, 30)}...` : label;
return (
- <div className="space-y-6">
- <DetailGroup title="Component Details">
- <div className="space-y-4">
- <label className="block">
- <span className="text-sm font-medium text-primary">Name</span>
- <Input
- value={component.label || ""}
- onChange={(e) => handleComponentUpdate({ label: e.target.value })}
- placeholder="Component name"
- className="mt-1"
- />
- </label>
-
- <label className="block">
- <span className="text-sm font-medium text-primary">
- Description
- </span>
- <TextArea
- value={component.description || ""}
- onChange={(e) =>
- handleComponentUpdate({ description: e.target.value })
- }
- placeholder="Component description"
- rows={4}
- className="mt-1"
- />
- </label>
- </div>
- </DetailGroup>
-
- <DetailGroup title="Configuration">
- <div className="space-y-4">
- {isAssistantAgent(component) && (
- <>
- <InputWithTooltip
- label="Name"
- tooltip="Name of the assistant agent"
- required
- >
- <Input
- value={component.config.name}
- onChange={(e) => handleConfigUpdate("name", e.target.value)}
- />
- </InputWithTooltip>
-
- {/* Model Client Section */}
-
- <div className="space-y-2">
- <span className="text-sm font-medium text-primary">
- Model Client
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "details",
+ label: (
+ <div className="flex items-center gap-2">
+ <User className="w-4 h-4 text-blue-500" />
+ <span className="font-medium">
+ Agent Details
+ <span className="text-xs font-normal text-secondary ml-2">
+ {displayName}
</span>
- {component.config.model_client ? (
- <div className="bg-secondary p-1 px-2 rounded-md">
- <div className="flex items-center justify-between">
- {" "}
- <span className="text-sm">
- {component.config.model_client.config.model}
+ </span>
+ </div>
+ ),
+ children: (
+ <>
+ {/* Component Details Section */}
+ <div className="border border-secondary rounded-lg p-3">
+ <div className="border-b border-secondary pb-2 mb-4">
+ <h3 className="text-sm font-medium text-primary">
+ Component Details
+ </h3>
+ </div>
+ <div className="space-y-4">
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Name
+ </span>
+ <Input
+ value={component.label || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ label: e.target.value })
+ }
+ placeholder="Component name"
+ className="mt-1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Description
+ </span>
+ <TextArea
+ value={component.description || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ description: e.target.value })
+ }
+ placeholder="Component description"
+ rows={4}
+ className="mt-1"
+ />
+ </label>
+
+ <div className="grid grid-cols-2 gap-4">
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Version
</span>
- <div className="flex items-center justify-between">
- {component.config.model_client && onNavigate && (
- <Button
- type="text"
- icon={<Edit className="w-4 h-4" />}
- onClick={() =>
- onNavigate(
- "model",
- component.config.model_client?.label || "",
- "model_client"
- )
- }
- >
- Configure Model
- </Button>
- )}
- </div>
- </div>
- </div>
- ) : (
- <div className="text-sm text-secondary text-center bg-secondary/50 p-4 rounded-md">
- No model configured
+ <InputNumber
+ min={1}
+ precision={0}
+ className="w-full mt-1"
+ placeholder="e.g., 1"
+ value={component.version || undefined}
+ onChange={(value) =>
+ handleComponentUpdate({ version: value || undefined })
+ }
+ />
+ </label>
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Component Version
+ </span>
+ <InputNumber
+ min={1}
+ precision={0}
+ className="w-full mt-1"
+ placeholder="e.g., 1"
+ value={component.component_version || undefined}
+ onChange={(value) =>
+ handleComponentUpdate({
+ component_version: value || undefined,
+ })
+ }
+ />
+ </label>
</div>
- )}
+ </div>
</div>
-
- <InputWithTooltip
- label="System Message"
- tooltip="System message for the agent"
- >
- <TextArea
- rows={4}
- value={component.config.system_message}
- onChange={(e) =>
- handleConfigUpdate("system_message", e.target.value)
- }
- />
- </InputWithTooltip>
-
- {/* Tools Section */}
- <div className="space-y-2">
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium text-primary">
- Tools
- </span>
- <Button
- type="dashed"
- size="small"
- onClick={handleAddTool}
- icon={<PlusCircle className="w-4 h-4" />}
- >
- Add Tool
- </Button>
+ </>
+ ),
+ },
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-green-500" />
+ <span className="font-medium">Agent Configuration</span>
+ </div>
+ ),
+ children: (
+ <>
+ {/* Configuration Section */}
+ <div className="border border-secondary rounded-lg p-3">
+ <div className="border-b border-secondary pb-2 mb-4">
+ <h3 className="text-sm font-medium text-primary">
+ Configuration
+ </h3>
</div>
- <div className="space-y-2">
- {component.config.tools?.map((tool, index) => (
- <div
- key={(tool.label || "") + index}
- className="bg-secondary p-1 px-2 rounded-md"
- >
+ <div className="space-y-4">
+ {isAssistantAgent(component) && (
+ <>
+ <InputWithTooltip
+ label="Name"
+ tooltip="Name of the assistant agent"
+ required
+ >
+ <Input
+ value={component.config.name}
+ onChange={(e) =>
+ handleConfigUpdate("name", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+
+ {/* Model Client Section */}
+
+ <div className="space-y-2">
+ <span className="text-sm font-medium text-primary">
+ Model Client
+ </span>
+ {component.config.model_client ? (
+ <div className="bg-secondary p-1 px-2 rounded-md">
+ <div className="flex items-center justify-between">
+ {" "}
+ <span className="text-sm">
+ {component.config.model_client.config.model}
+ </span>
+ <div className="flex items-center justify-between">
+ {component.config.model_client &&
+ onNavigate && (
+ <Button
+ type="text"
+ icon={<Edit className="w-4 h-4" />}
+ onClick={() =>
+ onNavigate(
+ "model",
+ component.config.model_client
+ ?.label || "",
+ "model_client"
+ )
+ }
+ >
+ Configure Model
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="text-sm text-secondary text-center bg-secondary/50 p-4 rounded-md">
+ No model configured
+ </div>
+ )}
+ </div>
+
+ <InputWithTooltip
+ label="System Message"
+ tooltip="System message for the agent"
+ >
+ <TextArea
+ rows={4}
+ value={component.config.system_message}
+ onChange={(e) =>
+ handleConfigUpdate("system_message", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+
<div className="flex items-center justify-between">
- <span className="text-sm">
- {tool.config.name || tool.label || ""}
+ <span className="text-sm font-medium text-primary">
+ Reflect on Tool Use
</span>
- <div className="flex items-center gap-2">
- {onNavigate && (
- <Button
- type="text"
- icon={<Edit className="w-4 h-4" />}
- onClick={() =>
- onNavigate(
- "tool",
- tool.config.name || tool.label || "",
- "tools"
- )
- }
- />
- )}
- <Button
- type="text"
- danger
- icon={<Trash2 className="w-4 h-4" />}
- onClick={() => handleRemoveTool(index)}
- />
- </div>
+ <Switch
+ checked={component.config.reflect_on_tool_use}
+ onChange={(checked) =>
+ handleConfigUpdate("reflect_on_tool_use", checked)
+ }
+ />
</div>
- </div>
- ))}
- {(!component.config.tools ||
- component.config.tools.length === 0) && (
- <div className="text-sm text-secondary text-center bg-secondary/50 p-4 rounded-md">
- No tools configured
- </div>
+
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Stream Model Client
+ </span>
+ <Switch
+ checked={component.config.model_client_stream}
+ onChange={(checked) =>
+ handleConfigUpdate("model_client_stream", checked)
+ }
+ />
+ </div>
+
+ <InputWithTooltip
+ label="Tool Call Summary Format"
+ tooltip="Format for tool call summaries"
+ >
+ <Input
+ value={component.config.tool_call_summary_format}
+ onChange={(e) =>
+ handleConfigUpdate(
+ "tool_call_summary_format",
+ e.target.value
+ )
+ }
+ />
+ </InputWithTooltip>
+ </>
)}
- </div>
- </div>
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium text-primary">
- Reflect on Tool Use
- </span>
- <Switch
- checked={component.config.reflect_on_tool_use}
- onChange={(checked) =>
- handleConfigUpdate("reflect_on_tool_use", checked)
- }
- />
- </div>
+ {isUserProxyAgent(component) && (
+ <InputWithTooltip
+ label="Name"
+ tooltip="Name of the user proxy agent"
+ required
+ >
+ <Input
+ value={component.config.name}
+ onChange={(e) =>
+ handleConfigUpdate("name", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+ )}
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium text-primary">
- Stream Model Client
- </span>
- <Switch
- checked={component.config.model_client_stream}
- onChange={(checked) =>
- handleConfigUpdate("model_client_stream", checked)
- }
- />
+ {isWebSurferAgent(component) && (
+ <>
+ <InputWithTooltip
+ label="Name"
+ tooltip="Name of the web surfer agent"
+ required
+ >
+ <Input
+ value={component.config.name}
+ onChange={(e) =>
+ handleConfigUpdate("name", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Start Page"
+ tooltip="URL to start browsing from"
+ >
+ <Input
+ value={component.config.start_page || ""}
+ onChange={(e) =>
+ handleConfigUpdate("start_page", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Downloads Folder"
+ tooltip="Folder path to save downloads"
+ >
+ <Input
+ value={component.config.downloads_folder || ""}
+ onChange={(e) =>
+ handleConfigUpdate(
+ "downloads_folder",
+ e.target.value
+ )
+ }
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Debug Directory"
+ tooltip="Directory for debugging logs"
+ >
+ <Input
+ value={component.config.debug_dir || ""}
+ onChange={(e) =>
+ handleConfigUpdate("debug_dir", e.target.value)
+ }
+ />
+ </InputWithTooltip>
+
+ {/* Added Model Client Section for WebSurferAgent */}
+ <div className="space-y-2">
+ <span className="text-sm font-medium text-primary">
+ Model Client
+ </span>
+ {component.config.model_client ? (
+ <div className="bg-secondary p-1 px-2 rounded-md">
+ <div className="flex items-center justify-between">
+ <span className="text-sm">
+ {component.config.model_client.config.model}
+ </span>
+ <div className="flex items-center justify-between">
+ {onNavigate && (
+ <Button
+ type="text"
+ icon={<Edit className="w-4 h-4" />}
+ onClick={() =>
+ onNavigate(
+ "model",
+ component.config.model_client?.label ||
+ "",
+ "model_client"
+ )
+ }
+ >
+ Configure Model
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="text-sm text-secondary text-center bg-secondary/50 p-4 rounded-md">
+ No model configured
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Headless
+ </span>
+ <Switch
+ checked={component.config.headless || false}
+ onChange={(checked) =>
+ handleConfigUpdate("headless", checked)
+ }
+ />
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Animate Actions
+ </span>
+ <Switch
+ checked={component.config.animate_actions || false}
+ onChange={(checked) =>
+ handleConfigUpdate("animate_actions", checked)
+ }
+ />
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Save Screenshots
+ </span>
+ <Switch
+ checked={
+ component.config.to_save_screenshots || false
+ }
+ onChange={(checked) =>
+ handleConfigUpdate("to_save_screenshots", checked)
+ }
+ />
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Use OCR
+ </span>
+ <Switch
+ checked={component.config.use_ocr || false}
+ onChange={(checked) =>
+ handleConfigUpdate("use_ocr", checked)
+ }
+ />
+ </div>
+ <InputWithTooltip
+ label="Browser Channel"
+ tooltip="Channel for the browser (e.g. beta, stable)"
+ >
+ <Input
+ value={component.config.browser_channel || ""}
+ onChange={(e) =>
+ handleConfigUpdate(
+ "browser_channel",
+ e.target.value
+ )
+ }
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Browser Data Directory"
+ tooltip="Directory for browser profile data"
+ >
+ <Input
+ value={component.config.browser_data_dir || ""}
+ onChange={(e) =>
+ handleConfigUpdate(
+ "browser_data_dir",
+ e.target.value
+ )
+ }
+ />
+ </InputWithTooltip>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Resize Viewport
+ </span>
+ <Switch
+ checked={component.config.to_resize_viewport || false}
+ onChange={(checked) =>
+ handleConfigUpdate("to_resize_viewport", checked)
+ }
+ />
+ </div>
+ </>
+ )}
+ </div>
</div>
- <InputWithTooltip
- label="Tool Call Summary Format"
- tooltip="Format for tool call summaries"
- >
- <Input
- value={component.config.tool_call_summary_format}
- onChange={(e) =>
- handleConfigUpdate(
- "tool_call_summary_format",
- e.target.value
- )
- }
- />
- </InputWithTooltip>
- </>
- )}
-
- {isUserProxyAgent(component) && (
- <InputWithTooltip
- label="Name"
- tooltip="Name of the user proxy agent"
- required
- >
- <Input
- value={component.config.name}
- onChange={(e) => handleConfigUpdate("name", e.target.value)}
- />
- </InputWithTooltip>
- )}
-
- {isWebSurferAgent(component) && (
- <>
- <InputWithTooltip
- label="Name"
- tooltip="Name of the web surfer agent"
- required
- >
- <Input
- value={component.config.name}
- onChange={(e) => handleConfigUpdate("name", e.target.value)}
- />
- </InputWithTooltip>
- <InputWithTooltip
- label="Start Page"
- tooltip="URL to start browsing from"
- >
- <Input
- value={component.config.start_page || ""}
- onChange={(e) =>
- handleConfigUpdate("start_page", e.target.value)
- }
- />
- </InputWithTooltip>
- <InputWithTooltip
- label="Downloads Folder"
- tooltip="Folder path to save downloads"
- >
- <Input
- value={component.config.downloads_folder || ""}
- onChange={(e) =>
- handleConfigUpdate("downloads_folder", e.target.value)
- }
- />
- </InputWithTooltip>
- <InputWithTooltip
- label="Debug Directory"
- tooltip="Directory for debugging logs"
- >
- <Input
- value={component.config.debug_dir || ""}
- onChange={(e) =>
- handleConfigUpdate("debug_dir", e.target.value)
- }
- />
- </InputWithTooltip>
-
- {/* Added Model Client Section for WebSurferAgent */}
- <div className="space-y-2">
- <span className="text-sm font-medium text-primary">
- Model Client
- </span>
- {component.config.model_client ? (
- <div className="bg-secondary p-1 px-2 rounded-md">
+ {/* Workbench Management Section - Only for AssistantAgent */}
+ {isAssistantAgent(component) && (
+ <div className="border border-secondary rounded-lg p-3">
+ <div className="border-b border-secondary pb-2 mb-4">
+ <h3 className="text-sm font-medium text-primary">
+ Workbench Management
+ </h3>
+ </div>
+ <div className="space-y-4">
<div className="flex items-center justify-between">
- <span className="text-sm">
- {component.config.model_client.config.model}
+ <span className="text-sm font-medium text-primary">
+ Workbenches (
+ {
+ normalizeWorkbenches(component.config.workbench)
+ .length
+ }
+ )
</span>
- <div className="flex items-center justify-between">
- {onNavigate && (
- <Button
- type="text"
- icon={<Edit className="w-4 h-4" />}
- onClick={() =>
- onNavigate(
- "model",
- component.config.model_client?.label || "",
- "model_client"
- )
+ <Dropdown
+ menu={{
+ items: [
+ {
+ key: "static",
+ label: (
+ <div>
+ <div>Static Workbench</div>
+ <div className="text-xs text-gray-500">
+ Collection of custom tools
+ </div>
+ </div>
+ ),
+ icon: <Wrench className="w-4 h-4" />,
+ onClick: addStaticWorkbench,
+ },
+ {
+ type: "divider",
+ },
+ {
+ key: "stdio-mcp",
+ label: (
+ <div>
+ <div>Stdio MCP Workbench</div>
+ <div className="text-xs text-gray-500">
+ Connect to local MCP servers
+ </div>
+ </div>
+ ),
+ icon: <PlusCircle className="w-4 h-4" />,
+ onClick: addStdioMcpWorkbench,
+ },
+ {
+ key: "sse-mcp",
+ label: (
+ <div>
+ <div>SSE MCP Workbench</div>
+ <div className="text-xs text-gray-500">
+ Connect via Server-Sent Events
+ </div>
+ </div>
+ ),
+ icon: <PlusCircle className="w-4 h-4" />,
+ onClick: addSseMcpWorkbench,
+ },
+ {
+ key: "streamable-mcp",
+ label: (
+ <div>
+ <div>Streamable MCP Workbench</div>
+ <div className="text-xs text-gray-500">
+ Connect via HTTP streaming
+ </div>
+ </div>
+ ),
+ icon: <PlusCircle className="w-4 h-4" />,
+ onClick: addStreamableMcpWorkbench,
+ },
+ ],
+ }}
+ trigger={["click"]}
+ >
+ <Button
+ type="dashed"
+ size="small"
+ icon={<PlusCircle className="w-4 h-4" />}
+ >
+ Add Workbench <ChevronDown className="w-3 h-3 ml-1" />
+ </Button>
+ </Dropdown>
+ </div>
+
+ <div className="space-y-3">
+ {normalizeWorkbenches(component.config.workbench).map(
+ (
+ workbench: Component<WorkbenchConfig>,
+ workbenchIndex: number
+ ) => {
+ // Get tool count for display
+ const getToolCount = () => {
+ if (isStaticWorkbench(workbench)) {
+ return (
+ (workbench.config as StaticWorkbenchConfig)
+ .tools?.length || 0
+ );
}
- >
- Configure Model
- </Button>
- )}
- </div>
+ // For MCP workbenches, we don't have a static count
+ return null;
+ };
+
+ const toolCount = getToolCount();
+
+ return (
+ <div
+ key={workbenchIndex}
+ className="bg-secondary/30 p-4 rounded-lg border border-gray-200"
+ >
+ {/* Workbench Header */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <div>
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">
+ {workbench.label ||
+ workbench.provider.split(".").pop()}
+ </span>
+ {/* Show tool count for static workbenches */}
+ {toolCount !== null && (
+ <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded">
+ {toolCount}{" "}
+ {toolCount === 1 ? "tool" : "tools"}
+ </span>
+ )}
+ {/* Show MCP indicator for MCP workbenches */}
+ {isMcpWorkbench(workbench) && (
+ <span className="text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded">
+ MCP Server
+ </span>
+ )}
+ </div>
+ <div className="text-xs text-gray-500 mt-1">
+ Provider: {workbench.provider}
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ {onNavigate && (
+ <Button
+ type="text"
+ icon={<Edit className="w-4 h-4" />}
+ onClick={() => {
+ // Navigate to workbench editor with proper index
+ onNavigate(
+ "workbench",
+ workbench.label ||
+ `workbench-${workbenchIndex}`,
+ "workbench",
+ workbenchIndex // Pass the index for proper identification
+ );
+ }}
+ />
+ )}
+ <Button
+ type="text"
+ danger
+ icon={<Trash2 className="w-4 h-4" />}
+ onClick={() => {
+ const normalizedWorkbenches =
+ normalizeWorkbenches(
+ component.config.workbench
+ );
+ const updatedWorkbenches = [
+ ...normalizedWorkbenches,
+ ];
+ updatedWorkbenches.splice(
+ workbenchIndex,
+ 1
+ );
+ handleConfigUpdate(
+ "workbench",
+ updatedWorkbenches
+ );
+ }}
+ />
+ </div>
+ </div>
+
+ {/* Show tools for StaticWorkbench */}
+ {isStaticWorkbench(workbench) &&
+ (workbench.config as StaticWorkbenchConfig)
+ .tools &&
+ (workbench.config as StaticWorkbenchConfig)
+ .tools.length > 0 && (
+ <div className="mt-3">
+ <div className="flex flex-wrap gap-1">
+ {(
+ workbench.config as StaticWorkbenchConfig
+ ).tools.map((tool, toolIndex) => (
+ <span
+ key={toolIndex}
+ className="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200"
+ >
+ <Wrench className="w-3 h-3 mr-1" />
+ {tool.config.name ||
+ tool.label ||
+ `Tool ${toolIndex + 1}`}
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ }
+ )}
+
+ {(() => {
+ const workbenches = normalizeWorkbenches(
+ component.config.workbench
+ );
+ return (
+ workbenches.length === 0 && (
+ <div className="text-sm text-secondary text-center bg-secondary/50 p-4 rounded-md">
+ No workbenches configured. Add a workbench to
+ provide tools to this agent.
+ </div>
+ )
+ );
+ })()}
</div>
</div>
- ) : (
- <div className="text-sm text-secondary text-center bg-secondary/50 p-4 rounded-md">
- No model configured
- </div>
- )}
- </div>
-
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium text-primary">
- Headless
- </span>
- <Switch
- checked={component.config.headless || false}
- onChange={(checked) =>
- handleConfigUpdate("headless", checked)
- }
- />
- </div>
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium text-primary">
- Animate Actions
- </span>
- <Switch
- checked={component.config.animate_actions || false}
- onChange={(checked) =>
- handleConfigUpdate("animate_actions", checked)
- }
- />
- </div>
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium text-primary">
- Save Screenshots
- </span>
- <Switch
- checked={component.config.to_save_screenshots || false}
- onChange={(checked) =>
- handleConfigUpdate("to_save_screenshots", checked)
- }
- />
- </div>
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium text-primary">
- Use OCR
- </span>
- <Switch
- checked={component.config.use_ocr || false}
- onChange={(checked) => handleConfigUpdate("use_ocr", checked)}
- />
- </div>
- <InputWithTooltip
- label="Browser Channel"
- tooltip="Channel for the browser (e.g. beta, stable)"
- >
- <Input
- value={component.config.browser_channel || ""}
- onChange={(e) =>
- handleConfigUpdate("browser_channel", e.target.value)
- }
- />
- </InputWithTooltip>
- <InputWithTooltip
- label="Browser Data Directory"
- tooltip="Directory for browser profile data"
- >
- <Input
- value={component.config.browser_data_dir || ""}
- onChange={(e) =>
- handleConfigUpdate("browser_data_dir", e.target.value)
- }
- />
- </InputWithTooltip>
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium text-primary">
- Resize Viewport
- </span>
- <Switch
- checked={component.config.to_resize_viewport || false}
- onChange={(checked) =>
- handleConfigUpdate("to_resize_viewport", checked)
- }
- />
- </div>
+ </div>
+ )}
</>
- )}
- </div>
- </DetailGroup>
- </div>
+ ),
+ },
+ ]}
+ />
);
};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/fields.tsx
index 3edd2abad..f89445355 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/fields.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/fields.tsx
@@ -1,5 +1,5 @@
import React from "react";
-import { Button, Form, Input } from "antd";
+import { Button, Form, Input, InputNumber } from "antd";
import {
Component,
@@ -12,6 +12,7 @@ import {
isModelComponent,
isToolComponent,
isTerminationComponent,
+ isWorkbenchComponent,
} from "../../../../../types/guards";
import DetailGroup from "../detailgroup";
import { TeamFields } from "./team-fields";
@@ -19,8 +20,9 @@ import { AgentFields } from "./agent-fields";
import { ModelFields } from "./model-fields";
import { ToolFields } from "./tool-fields";
import { TerminationFields } from "./termination-fields";
+import { WorkbenchFields } from "./workbench";
import { Edit, MinusCircle, PlusCircle } from "lucide-react";
-import { EditPath } from "../node-editor";
+import { EditPath } from "../component-editor";
const { TextArea } = Input;
@@ -57,11 +59,27 @@ const NodeEditorFields: React.FC<NodeEditorFieldsProps> = ({
<TeamFields
component={component}
onNavigate={onNavigate}
- workingCopy={workingCopy}
- setWorkingCopy={setWorkingCopy}
- editPath={editPath}
- updateComponentAtPath={updateComponentAtPath}
- getCurrentComponent={getCurrentComponent}
+ onChange={(updates) => {
+ if (
+ workingCopy &&
+ setWorkingCopy &&
+ editPath &&
+ updateComponentAtPath
+ ) {
+ const updatedCopy = updateComponentAtPath(
+ workingCopy,
+ editPath,
+ updates
+ );
+ setWorkingCopy(updatedCopy);
+ }
+ }}
+ // onChange={onChange}
+ // workingCopy={workingCopy}
+ // setWorkingCopy={setWorkingCopy}
+ // editPath={editPath}
+ // updateComponentAtPath={updateComponentAtPath}
+ // getCurrentComponent={getCurrentComponent}
/>
</DetailGroup>
);
@@ -70,6 +88,21 @@ const NodeEditorFields: React.FC<NodeEditorFieldsProps> = ({
<DetailGroup title="Configuration">
<AgentFields
component={component}
+ onChange={(updates) => {
+ if (
+ workingCopy &&
+ setWorkingCopy &&
+ editPath &&
+ updateComponentAtPath
+ ) {
+ const updatedCopy = updateComponentAtPath(
+ workingCopy,
+ editPath,
+ updates
+ );
+ setWorkingCopy(updatedCopy);
+ }
+ }}
onNavigate={onNavigate}
workingCopy={workingCopy}
setWorkingCopy={setWorkingCopy}
@@ -82,33 +115,120 @@ const NodeEditorFields: React.FC<NodeEditorFieldsProps> = ({
} else if (isModelComponent(component)) {
specificFields = (
<DetailGroup title="Configuration">
- <ModelFields component={component} />
+ <ModelFields
+ component={component}
+ onChange={(updates) => {
+ if (
+ workingCopy &&
+ setWorkingCopy &&
+ editPath &&
+ updateComponentAtPath
+ ) {
+ const updatedCopy = updateComponentAtPath(
+ workingCopy,
+ editPath,
+ updates
+ );
+ setWorkingCopy(updatedCopy);
+ }
+ }}
+ />
</DetailGroup>
);
- } else if (isToolComponent(component)) {
+ } else if (isWorkbenchComponent(component)) {
specificFields = (
- <DetailGroup title="Configuration">
- <ToolFields
+ <DetailGroup title="Workbench Configuration">
+ <WorkbenchFields
component={component}
- workingCopy={workingCopy}
- setWorkingCopy={setWorkingCopy}
- editPath={editPath}
- updateComponentAtPath={updateComponentAtPath}
- getCurrentComponent={getCurrentComponent}
+ onChange={(updates) => {
+ if (
+ workingCopy &&
+ setWorkingCopy &&
+ editPath &&
+ updateComponentAtPath
+ ) {
+ const updatedCopy = updateComponentAtPath(
+ workingCopy,
+ editPath,
+ updates
+ );
+ setWorkingCopy(updatedCopy);
+ }
+ }}
/>
</DetailGroup>
);
- } else if (isTerminationComponent(component)) {
+ }
+ // NOTE: Individual tools are deprecated - use workbenches instead
+ // This is kept for backward compatibility during migration
+ // else if (isToolComponent(component)) {
+ // specificFields = (
+ // <DetailGroup title="Configuration">
+ // <ToolFields
+ // component={component}
+ // onChange={(updates) => {
+ // if (
+ // workingCopy &&
+ // setWorkingCopy &&
+ // editPath &&
+ // updateComponentAtPath
+ // ) {
+ // const updatedCopy = updateComponentAtPath(
+ // workingCopy,
+ // editPath,
+ // updates
+ // );
+ // setWorkingCopy(updatedCopy);
+ // }
+ // }}
+ // />
+ // </DetailGroup>
+ // );
+ // }
+ else if (isTerminationComponent(component)) {
specificFields = (
<DetailGroup title="Configuration">
<TerminationFields
component={component}
+ onChange={(updates) => {
+ if (
+ workingCopy &&
+ setWorkingCopy &&
+ editPath &&
+ updateComponentAtPath
+ ) {
+ const updatedCopy = updateComponentAtPath(
+ workingCopy,
+ editPath,
+ updates
+ );
+ setWorkingCopy(updatedCopy);
+ }
+ }}
onNavigate={onNavigate}
- workingCopy={workingCopy}
- setWorkingCopy={setWorkingCopy}
- editPath={editPath}
- updateComponentAtPath={updateComponentAtPath}
- getCurrentComponent={getCurrentComponent}
+ />
+ </DetailGroup>
+ );
+ } else if (isWorkbenchComponent(component)) {
+ specificFields = (
+ <DetailGroup title="Configuration">
+ <WorkbenchFields
+ component={component}
+ onChange={(updates) => {
+ if (
+ workingCopy &&
+ setWorkingCopy &&
+ editPath &&
+ updateComponentAtPath
+ ) {
+ const updatedCopy = updateComponentAtPath(
+ workingCopy,
+ editPath,
+ updates
+ );
+ setWorkingCopy(updatedCopy);
+ }
+ }}
/>
</DetailGroup>
);
@@ -137,6 +257,24 @@ export const CommonFields: React.FC = () => {
<Form.Item label="Description" name="description">
<TextArea rows={4} />
</Form.Item>
+ <div className="grid grid-cols-2 gap-4">
+ <Form.Item label="Version" name="version">
+ <InputNumber
+ min={1}
+ precision={0}
+ className="w-full"
+ placeholder="e.g., 1"
+ />
+ </Form.Item>
+ <Form.Item label="Component Version" name="component_version">
+ <InputNumber
+ min={1}
+ precision={0}
+ className="w-full"
+ placeholder="e.g., 1"
+ />
+ </Form.Item>
+ </div>
</>
);
};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/model-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/model-fields.tsx
index 21e2bf443..4126f7958 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/model-fields.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/model-fields.tsx
@@ -1,6 +1,7 @@
import React, { useCallback } from "react";
-import { Input, InputNumber, Select, Tooltip } from "antd";
-import { HelpCircle } from "lucide-react";
+import { Input, InputNumber, Select, Tooltip, Collapse } from "antd";
+import TextArea from "antd/es/input/TextArea";
+import { HelpCircle, Settings, User, Wrench } from "lucide-react";
import {
Component,
ComponentConfig,
@@ -11,8 +12,6 @@ import {
isAzureOpenAIModel,
isAnthropicModel,
} from "../../../../../types/guards";
-import DetailGroup from "../detailgroup";
-import TextArea from "antd/es/input/TextArea";
interface ModelFieldsProps {
component: Component<ModelConfig>;
@@ -412,77 +411,113 @@ export const ModelFields: React.FC<ModelFieldsProps> = ({
};
return (
- <div className="space-y-6">
- <DetailGroup title="Component Details">
- <div className="space-y-4">
- <label className="block">
- <span className="text-sm font-medium text-primary">Name</span>
- <Input
- value={component.label || ""}
- onChange={(e) => handleComponentUpdate({ label: e.target.value })}
- placeholder="Model name"
- className="mt-1"
- />
- </label>
-
- <label className="block">
- <span className="text-sm font-medium text-primary">
- Description
- </span>
- <TextArea
- value={component.description || ""}
- onChange={(e) =>
- handleComponentUpdate({ description: e.target.value })
- }
- placeholder="Model description"
- rows={4}
- className="mt-1"
- />
- </label>
- </div>
- </DetailGroup>
-
- <DetailGroup
- title={
- providerType === "azure"
- ? "Azure Configuration"
- : "Model Configuration"
- }
- >
- {renderFieldGroup(providerFields[providerType].modelConfig)}
- </DetailGroup>
-
- <DetailGroup title="Model Parameters">
- {renderFieldGroup(providerFields[providerType].modelParams)}
- </DetailGroup>
-
- {/* Only render tool configuration if it's an Anthropic model and has tools */}
- {providerType === "anthropic" &&
- (component.config as any).tool_choice === "custom" && (
- <DetailGroup title="Custom Tool Choice">
+ <Collapse
+ defaultActiveKey={["details", "configuration", "parameters"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "details",
+ label: (
+ <div className="flex items-center gap-2">
+ <User className="w-4 h-4 text-blue-500" />
+ <span className="font-medium">Component Details</span>
+ </div>
+ ),
+ children: (
<div className="space-y-4">
- <TextArea
- value={JSON.stringify(
- (component.config as any).tool_choice,
- null,
- 2
- )}
- onChange={(e) => {
- try {
- const value = JSON.parse(e.target.value);
- handleConfigUpdate("tool_choice" as FieldName, value);
- } catch (err) {
- // Handle invalid JSON
- console.error("Invalid JSON for tool_choice");
+ <label className="block">
+ <span className="text-sm font-medium text-primary">Name</span>
+ <Input
+ value={component.label || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ label: e.target.value })
}
- }}
- placeholder="Enter tool choice configuration as JSON"
- rows={4}
- />
+ placeholder="Model name"
+ className="mt-1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Description
+ </span>
+ <TextArea
+ value={component.description || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ description: e.target.value })
+ }
+ placeholder="Model description"
+ rows={4}
+ className="mt-1"
+ />
+ </label>
</div>
- </DetailGroup>
- )}
- </div>
+ ),
+ },
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-green-500" />
+ <span className="font-medium">
+ {providerType === "azure"
+ ? "Azure Configuration"
+ : "Model Configuration"}
+ </span>
+ </div>
+ ),
+ children: renderFieldGroup(providerFields[providerType].modelConfig),
+ },
+ {
+ key: "parameters",
+ label: (
+ <div className="flex items-center gap-2">
+ <Wrench className="w-4 h-4 text-orange-500" />
+ <span className="font-medium">Model Parameters</span>
+ </div>
+ ),
+ children: renderFieldGroup(providerFields[providerType].modelParams),
+ },
+ // Only render tool configuration if it's an Anthropic model and has tools
+ ...(providerType === "anthropic" &&
+ (component.config as any).tool_choice === "custom"
+ ? [
+ {
+ key: "tools",
+ label: (
+ <div className="flex items-center gap-2">
+ <Wrench className="w-4 h-4 text-purple-500" />
+ <span className="font-medium">Custom Tool Choice</span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ <TextArea
+ value={JSON.stringify(
+ (component.config as any).tool_choice,
+ null,
+ 2
+ )}
+ onChange={(e) => {
+ try {
+ const value = JSON.parse(e.target.value);
+ handleConfigUpdate("tool_choice" as FieldName, value);
+ } catch (err) {
+ // Handle invalid JSON
+ console.error("Invalid JSON for tool_choice");
+ }
+ }}
+ placeholder="Enter tool choice configuration as JSON"
+ rows={4}
+ />
+ </div>
+ ),
+ },
+ ]
+ : []),
+ ]}
+ />
);
};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/team-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/team-fields.tsx
index 9e02c9249..b82f416e1 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/team-fields.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/team-fields.tsx
@@ -1,15 +1,19 @@
import React, { useCallback } from "react";
-import { Input, Button } from "antd";
-import { Edit, Timer } from "lucide-react";
+import { Input, Button, Collapse } from "antd";
+import { Edit, Timer, User, Settings } from "lucide-react";
import {
Component,
TeamConfig,
ComponentConfig,
RoundRobinGroupChatConfig,
SelectorGroupChatConfig,
+ SwarmConfig,
} from "../../../../../types/datamodel";
-import { isSelectorTeam, isRoundRobinTeam } from "../../../../../types/guards";
-import DetailGroup from "../detailgroup";
+import {
+ isSelectorTeam,
+ isRoundRobinTeam,
+ isSwarmTeam,
+} from "../../../../../types/guards";
const { TextArea } = Input;
@@ -24,7 +28,12 @@ export const TeamFields: React.FC<TeamFieldsProps> = ({
onChange,
onNavigate,
}) => {
- if (!isSelectorTeam(component) && !isRoundRobinTeam(component)) return null;
+ if (
+ !isSelectorTeam(component) &&
+ !isRoundRobinTeam(component) &&
+ !isSwarmTeam(component)
+ )
+ return null;
const handleComponentUpdate = useCallback(
(updates: Partial<Component<ComponentConfig>>) => {
@@ -56,129 +65,203 @@ export const TeamFields: React.FC<TeamFieldsProps> = ({
[field]: value,
} as RoundRobinGroupChatConfig,
});
+ } else if (isSwarmTeam(component)) {
+ handleComponentUpdate({
+ config: {
+ ...(component as Component<SwarmConfig>).config,
+ [field]: value,
+ } as SwarmConfig,
+ });
}
},
[component, handleComponentUpdate]
);
return (
- <div className=" ">
- <DetailGroup title="Component Details">
- <div className="space-y-4">
- <label className="block">
- <span className="text-sm font-medium text-primary">Name</span>
- <Input
- value={component.label || ""}
- onChange={(e) => handleComponentUpdate({ label: e.target.value })}
- placeholder="Team name"
- className="mt-1"
- />
- </label>
+ <Collapse
+ defaultActiveKey={["details", "configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "details",
+ label: (
+ <div className="flex items-center gap-2">
+ <User className="w-4 h-4 text-blue-500" />
+ <span className="font-medium">Component Details</span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ <label className="block">
+ <span className="text-sm font-medium text-primary">Name</span>
+ <Input
+ value={component.label || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ label: e.target.value })
+ }
+ placeholder="Team name"
+ className="mt-1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Description
+ </span>
+ <TextArea
+ value={component.description || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ description: e.target.value })
+ }
+ placeholder="Team description"
+ rows={4}
+ className="mt-1"
+ />
+ </label>
+ </div>
+ ),
+ },
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-green-500" />
+ <span className="font-medium">Team Configuration</span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ {isSelectorTeam(component) && (
+ <div className="space-y-4">
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Selector Prompt
+ </span>
+ <TextArea
+ value={component.config.selector_prompt || ""}
+ onChange={(e) =>
+ handleConfigUpdate("selector_prompt", e.target.value)
+ }
+ placeholder="Prompt for the selector"
+ rows={4}
+ className="mt-1"
+ />
+ </label>
- <label className="block">
- <span className="text-sm font-medium text-primary">
- Description
- </span>
- <TextArea
- value={component.description || ""}
- onChange={(e) =>
- handleComponentUpdate({ description: e.target.value })
- }
- placeholder="Team description"
- rows={4}
- className="mt-1"
- />
- </label>
- </div>
- </DetailGroup>
+ <div className="space-y-2">
+ <h3 className="text-sm font-medium text-primary">Model</h3>
+ <div className="bg-secondary p-4 rounded-md">
+ {component.config.model_client ? (
+ <div className="flex items-center justify-between">
+ <span className="text-sm">
+ {component.config.model_client.config.model}
+ </span>
+ {onNavigate && (
+ <Button
+ type="text"
+ icon={<Edit className="w-4 h-4" />}
+ onClick={() =>
+ onNavigate(
+ "model",
+ component.config.model_client?.label || "",
+ "model_client"
+ )
+ }
+ />
+ )}
+ </div>
+ ) : (
+ <div className="text-sm text-secondary text-center">
+ No model configured
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
- <DetailGroup title="Configuration">
- {isSelectorTeam(component) && (
- <div className="space-y-4">
- <label className="block">
- <span className="text-sm font-medium text-primary">
- Selector Prompt
- </span>
- <TextArea
- value={component.config.selector_prompt || ""}
- onChange={(e) =>
- handleConfigUpdate("selector_prompt", e.target.value)
- }
- placeholder="Prompt for the selector"
- rows={4}
- className="mt-1"
- />
- </label>
+ {isSwarmTeam(component) && (
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <h3 className="text-sm font-medium text-primary">
+ Team Type
+ </h3>
+ <div className="bg-secondary p-4 rounded-md">
+ <div className="text-sm text-secondary">
+ Swarm team uses handoff messages to transfer control
+ between agents. Each agent specifies which agents they
+ can hand off to.
+ </div>
+ </div>
+ </div>
- <div className="space-y-2">
- <h3 className="text-sm font-medium text-primary">Model</h3>
- <div className="bg-secondary p-4 rounded-md">
- {component.config.model_client ? (
- <div className="flex items-center justify-between">
- <span className="text-sm">
- {component.config.model_client.config.model}
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Emit Team Events
</span>
- {onNavigate && (
- <Button
- type="text"
- icon={<Edit className="w-4 h-4" />}
- onClick={() =>
- onNavigate(
- "model",
- component.config.model_client?.label || "",
- "model_client"
+ <div className="mt-1">
+ <input
+ type="checkbox"
+ checked={component.config.emit_team_events || false}
+ onChange={(e) =>
+ handleConfigUpdate(
+ "emit_team_events",
+ e.target.checked
)
}
+ className="mr-2"
/>
- )}
- </div>
- ) : (
- <div className="text-sm text-secondary text-center">
- No model configured
- </div>
- )}
- </div>
- </div>
- </div>
- )}
+ <span className="text-sm text-secondary">
+ Enable team event emission for debugging and monitoring
+ </span>
+ </div>
+ </label>
+ </div>
+ )}
- <div className="space-y-2 mt-4">
- <h3 className="text-sm font-medium text-primary">
- Termination Condition
- </h3>
- <div className="bg-secondary p-4 rounded-md">
- {component.config.termination_condition ? (
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Timer className="w-4 h-4 text-secondary" />
- <span className="text-sm">
- {component.config.termination_condition.label ||
- component.config.termination_condition.component_type}
- </span>
+ <div className="space-y-2 mt-4">
+ <h3 className="text-sm font-medium text-primary">
+ Termination Condition
+ </h3>
+ <div className="bg-secondary p-4 rounded-md">
+ {component.config.termination_condition ? (
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Timer className="w-4 h-4 text-secondary" />
+ <span className="text-sm">
+ {component.config.termination_condition.label ||
+ component.config.termination_condition
+ .component_type}
+ </span>
+ </div>
+ {onNavigate && (
+ <Button
+ type="text"
+ icon={<Edit className="w-4 h-4" />}
+ onClick={() =>
+ onNavigate(
+ "termination",
+ component.config.termination_condition?.label ||
+ "",
+ "termination_condition"
+ )
+ }
+ />
+ )}
+ </div>
+ ) : (
+ <div className="text-sm text-secondary text-center">
+ No termination condition configured
+ </div>
+ )}
</div>
- {onNavigate && (
- <Button
- type="text"
- icon={<Edit className="w-4 h-4" />}
- onClick={() =>
- onNavigate(
- "termination",
- component.config.termination_condition?.label || "",
- "termination_condition"
- )
- }
- />
- )}
- </div>
- ) : (
- <div className="text-sm text-secondary text-center">
- No termination condition configured
</div>
- )}
- </div>
- </div>
- </DetailGroup>
- </div>
+ </div>
+ ),
+ },
+ ]}
+ />
);
};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/termination-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/termination-fields.tsx
index 17bd19f3f..281a7cc30 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/termination-fields.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/termination-fields.tsx
@@ -1,19 +1,47 @@
import React, { useCallback, useState } from "react";
-import { Input, InputNumber, Button, Select, Tooltip } from "antd";
-import { PlusCircle, MinusCircle, Edit, HelpCircle } from "lucide-react";
+import {
+ Input,
+ InputNumber,
+ Button,
+ Select,
+ Tooltip,
+ Collapse,
+ Checkbox,
+} from "antd";
+import {
+ PlusCircle,
+ MinusCircle,
+ Edit,
+ HelpCircle,
+ Timer,
+ Settings,
+ User,
+} from "lucide-react";
import {
Component,
ComponentConfig,
TerminationConfig,
+ TokenUsageTerminationConfig,
+ TimeoutTerminationConfig,
+ HandoffTerminationConfig,
+ SourceMatchTerminationConfig,
+ TextMessageTerminationConfig,
+ ExternalTerminationConfig,
} from "../../../../../types/datamodel";
import {
isOrTermination,
isMaxMessageTermination,
isTextMentionTermination,
isCombinationTermination,
+ isStopMessageTermination,
+ isTokenUsageTermination,
+ isHandoffTermination,
+ isTimeoutTermination,
+ isExternalTermination,
+ isSourceMatchTermination,
+ isTextMessageTermination,
} from "../../../../../types/guards";
import { PROVIDERS } from "../../../../../types/guards";
-import DetailGroup from "../detailgroup";
interface TerminationFieldsProps {
component: Component<TerminationConfig>;
@@ -37,6 +65,51 @@ const TERMINATION_TYPES = {
text: "TERMINATE",
},
},
+ STOP_MESSAGE: {
+ label: "Stop Message",
+ provider: PROVIDERS.STOP_MESSAGE,
+ defaultConfig: {},
+ },
+ TOKEN_USAGE: {
+ label: "Token Usage",
+ provider: PROVIDERS.TOKEN_USAGE,
+ defaultConfig: {
+ max_total_token: 1000,
+ },
+ },
+ TIMEOUT: {
+ label: "Timeout",
+ provider: PROVIDERS.TIMEOUT,
+ defaultConfig: {
+ timeout_seconds: 300,
+ },
+ },
+ HANDOFF: {
+ label: "Handoff",
+ provider: PROVIDERS.HANDOFF,
+ defaultConfig: {
+ target: "",
+ },
+ },
+ SOURCE_MATCH: {
+ label: "Source Match",
+ provider: PROVIDERS.SOURCE_MATCH,
+ defaultConfig: {
+ sources: [],
+ },
+ },
+ TEXT_MESSAGE: {
+ label: "Text Message",
+ provider: PROVIDERS.TEXT_MESSAGE,
+ defaultConfig: {
+ source: "",
+ },
+ },
+ EXTERNAL: {
+ label: "External",
+ provider: PROVIDERS.EXTERNAL,
+ defaultConfig: {},
+ },
};
const InputWithTooltip: React.FC<{
@@ -124,116 +197,476 @@ export const TerminationFields: React.FC<TerminationFieldsProps> = ({
if (isCombinationTermination(component)) {
return (
- <DetailGroup title="Termination Conditions">
- <div className="space-y-4">
- <div className="flex justify-between items-center">
- <Button
- type="dashed"
- onClick={() => setShowAddCondition(true)}
- icon={<PlusCircle className="w-4 h-4" />}
- className="w-full"
- >
- Add Condition
- </Button>
- </div>
-
- {showAddCondition && (
- <div className="border rounded p-4 space-y-4">
+ <Collapse
+ defaultActiveKey={["conditions"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "conditions",
+ label: (
+ <div className="flex items-center gap-2">
+ <Timer className="w-4 h-4 text-blue-500" />
+ <span className="font-medium">Termination Conditions</span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ <div className="flex justify-between items-center">
+ <Button
+ type="dashed"
+ onClick={() => setShowAddCondition(true)}
+ icon={<PlusCircle className="w-4 h-4" />}
+ className="w-full"
+ >
+ Add Condition
+ </Button>
+ </div>
+
+ {showAddCondition && (
+ <div className="border rounded p-4 space-y-4">
+ <InputWithTooltip
+ label="Condition Type"
+ tooltip="Select the type of termination condition to add"
+ >
+ <Select
+ value={selectedConditionType}
+ onChange={setSelectedConditionType}
+ className="w-full"
+ >
+ {Object.entries(TERMINATION_TYPES).map(
+ ([key, value]) => (
+ <Select.Option key={key} value={key}>
+ {value.label}
+ </Select.Option>
+ )
+ )}
+ </Select>
+ </InputWithTooltip>
+ <Button
+ onClick={handleAddCondition}
+ disabled={!selectedConditionType}
+ className="w-full"
+ >
+ Add
+ </Button>
+ </div>
+ )}
+
+ <div className="space-y-2">
+ {component.config.conditions?.map((condition, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <Button
+ onClick={() =>
+ onNavigate?.(
+ condition.component_type,
+ condition.label || "",
+ "conditions"
+ )
+ }
+ className="w-full flex justify-between items-center"
+ >
+ <span>
+ {condition.label || `Condition ${index + 1}`}
+ </span>
+ <Edit className="w-4 h-4" />
+ </Button>
+ <Button
+ type="text"
+ danger
+ icon={<MinusCircle className="w-4 h-4" />}
+ onClick={() => handleRemoveCondition(index)}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ ),
+ },
+ ]}
+ />
+ );
+ }
+
+ if (isMaxMessageTermination(component)) {
+ return (
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-green-500" />
+ <span className="font-medium">Max Messages Configuration</span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ <InputWithTooltip
+ label="Max Messages"
+ tooltip="Maximum number of messages before termination"
+ >
+ <InputNumber
+ min={1}
+ value={component.config.max_messages}
+ onChange={(value) =>
+ handleComponentUpdate({
+ config: { max_messages: value },
+ })
+ }
+ className="w-full"
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Include Agent Events"
+ tooltip="Include agent events in the message count, not just chat messages"
+ >
+ <Checkbox
+ checked={component.config.include_agent_event || false}
+ onChange={(e) =>
+ handleComponentUpdate({
+ config: { include_agent_event: e.target.checked },
+ })
+ }
+ >
+ Include agent events in message count
+ </Checkbox>
+ </InputWithTooltip>
+ </div>
+ ),
+ },
+ ]}
+ />
+ );
+ }
+
+ if (isTextMentionTermination(component)) {
+ return (
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-purple-500" />
+ <span className="font-medium">Text Mention Configuration</span>
+ </div>
+ ),
+ children: (
<InputWithTooltip
- label="Condition Type"
- tooltip="Select the type of termination condition to add"
+ label="Termination Text"
+ tooltip="Text that triggers termination when mentioned"
>
- <Select
- value={selectedConditionType}
- onChange={setSelectedConditionType}
- className="w-full"
+ <Input
+ value={component.config.text}
+ onChange={(e) =>
+ handleComponentUpdate({
+ config: { text: e.target.value },
+ })
+ }
+ />
+ </InputWithTooltip>
+ ),
+ },
+ ]}
+ />
+ );
+ }
+
+ if (isStopMessageTermination(component)) {
+ return (
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-red-500" />
+ <span className="font-medium">Stop Message Configuration</span>
+ </div>
+ ),
+ children: (
+ <div className="text-sm text-gray-600">
+ This termination condition triggers when a StopMessage is
+ received. No additional configuration is required.
+ </div>
+ ),
+ },
+ ]}
+ />
+ );
+ }
+
+ if (isTokenUsageTermination(component)) {
+ const tokenComponent = component as Component<TokenUsageTerminationConfig>;
+ return (
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-yellow-500" />
+ <span className="font-medium">Token Usage Configuration</span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ <InputWithTooltip
+ label="Max Total Tokens"
+ tooltip="Maximum total number of tokens allowed"
>
- {Object.entries(TERMINATION_TYPES).map(([key, value]) => (
- <Select.Option key={key} value={key}>
- {value.label}
- </Select.Option>
- ))}
- </Select>
+ <InputNumber
+ min={1}
+ value={tokenComponent.config.max_total_token}
+ onChange={(value) =>
+ handleComponentUpdate({
+ config: { max_total_token: value },
+ })
+ }
+ className="w-full"
+ placeholder="e.g., 1000"
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Max Prompt Tokens"
+ tooltip="Maximum number of prompt tokens allowed"
+ >
+ <InputNumber
+ min={1}
+ value={tokenComponent.config.max_prompt_token}
+ onChange={(value) =>
+ handleComponentUpdate({
+ config: { max_prompt_token: value },
+ })
+ }
+ className="w-full"
+ placeholder="e.g., 800"
+ />
+ </InputWithTooltip>
+ <InputWithTooltip
+ label="Max Completion Tokens"
+ tooltip="Maximum number of completion tokens allowed"
+ >
+ <InputNumber
+ min={1}
+ value={tokenComponent.config.max_completion_token}
+ onChange={(value) =>
+ handleComponentUpdate({
+ config: { max_completion_token: value },
+ })
+ }
+ className="w-full"
+ placeholder="e.g., 200"
+ />
+ </InputWithTooltip>
+ </div>
+ ),
+ },
+ ]}
+ />
+ );
+ }
+
+ if (isTimeoutTermination(component)) {
+ const timeoutComponent = component as Component<TimeoutTerminationConfig>;
+ return (
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Timer className="w-4 h-4 text-orange-500" />
+ <span className="font-medium">Timeout Configuration</span>
+ </div>
+ ),
+ children: (
+ <InputWithTooltip
+ label="Timeout (seconds)"
+ tooltip="Maximum duration in seconds before termination"
+ >
+ <InputNumber
+ min={1}
+ value={timeoutComponent.config.timeout_seconds}
+ onChange={(value) =>
+ handleComponentUpdate({
+ config: { timeout_seconds: value },
+ })
+ }
+ className="w-full"
+ placeholder="e.g., 300"
+ />
</InputWithTooltip>
- <Button
- onClick={handleAddCondition}
- disabled={!selectedConditionType}
- className="w-full"
+ ),
+ },
+ ]}
+ />
+ );
+ }
+
+ if (isHandoffTermination(component)) {
+ const handoffComponent = component as Component<HandoffTerminationConfig>;
+ return (
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <User className="w-4 h-4 text-blue-500" />
+ <span className="font-medium">Handoff Configuration</span>
+ </div>
+ ),
+ children: (
+ <InputWithTooltip
+ label="Target Agent"
+ tooltip="Agent to handoff to before termination"
>
- Add
- </Button>
- </div>
- )}
-
- <div className="space-y-2">
- {component.config.conditions?.map((condition, index) => (
- <div key={index} className="flex items-center gap-2">
- <Button
- onClick={() =>
- onNavigate?.(
- condition.component_type,
- condition.label || "",
- "conditions"
- )
+ <Input
+ value={handoffComponent.config.target}
+ onChange={(e) =>
+ handleComponentUpdate({
+ config: { target: e.target.value },
+ })
}
- className="w-full flex justify-between items-center"
- >
- <span>{condition.label || `Condition ${index + 1}`}</span>
- <Edit className="w-4 h-4" />
- </Button>
- <Button
- type="text"
- danger
- icon={<MinusCircle className="w-4 h-4" />}
- onClick={() => handleRemoveCondition(index)}
+ placeholder="e.g., agent_name"
/>
+ </InputWithTooltip>
+ ),
+ },
+ ]}
+ />
+ );
+ }
+
+ if (isSourceMatchTermination(component)) {
+ const sourceMatchComponent =
+ component as Component<SourceMatchTerminationConfig>;
+ return (
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-indigo-500" />
+ <span className="font-medium">Source Match Configuration</span>
</div>
- ))}
- </div>
- </div>
- </DetailGroup>
+ ),
+ children: (
+ <InputWithTooltip
+ label="Source Names"
+ tooltip="List of source names to match (comma-separated)"
+ >
+ <Input
+ value={sourceMatchComponent.config.sources?.join(", ") || ""}
+ onChange={(e) =>
+ handleComponentUpdate({
+ config: {
+ sources: e.target.value
+ .split(",")
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0),
+ },
+ })
+ }
+ placeholder="e.g., agent1, agent2"
+ />
+ </InputWithTooltip>
+ ),
+ },
+ ]}
+ />
);
}
- if (isMaxMessageTermination(component)) {
+ if (isTextMessageTermination(component)) {
+ const textMessageComponent =
+ component as Component<TextMessageTerminationConfig>;
return (
- <DetailGroup title="Max Messages Configuration">
- <InputWithTooltip
- label="Max Messages"
- tooltip="Maximum number of messages before termination"
- >
- <InputNumber
- min={1}
- value={component.config.max_messages}
- onChange={(value) =>
- handleComponentUpdate({
- config: { max_messages: value },
- })
- }
- className="w-full"
- />
- </InputWithTooltip>
- </DetailGroup>
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-pink-500" />
+ <span className="font-medium">Text Message Configuration</span>
+ </div>
+ ),
+ children: (
+ <InputWithTooltip
+ label="Source Filter (optional)"
+ tooltip="Filter to only terminate on text messages from specific source"
+ >
+ <Input
+ value={textMessageComponent.config.source || ""}
+ onChange={(e) =>
+ handleComponentUpdate({
+ config: { source: e.target.value || undefined },
+ })
+ }
+ placeholder="e.g., agent_name (leave empty for any source)"
+ />
+ </InputWithTooltip>
+ ),
+ },
+ ]}
+ />
);
}
- if (isTextMentionTermination(component)) {
+ if (isExternalTermination(component)) {
return (
- <DetailGroup title="Text Mention Configuration">
- <InputWithTooltip
- label="Termination Text"
- tooltip="Text that triggers termination when mentioned"
- >
- <Input
- value={component.config.text}
- onChange={(e) =>
- handleComponentUpdate({
- config: { text: e.target.value },
- })
- }
- />
- </InputWithTooltip>
- </DetailGroup>
+ <Collapse
+ defaultActiveKey={["configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-gray-500" />
+ <span className="font-medium">
+ External Termination Configuration
+ </span>
+ </div>
+ ),
+ children: (
+ <div className="text-sm text-gray-600">
+ This termination condition is controlled externally by calling
+ the set() method. No additional configuration is required.
+ </div>
+ ),
+ },
+ ]}
+ />
);
}
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/tool-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/tool-fields.tsx
index 00013b752..1b58bef11 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/tool-fields.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/tool-fields.tsx
@@ -1,6 +1,6 @@
import React, { useCallback, useRef, useState } from "react";
-import { Input, Switch, Select, Button, Space } from "antd";
-import { PlusCircle, MinusCircle } from "lucide-react";
+import { Input, Switch, Select, Button, Space, Collapse } from "antd";
+import { PlusCircle, MinusCircle, User, Settings, Code } from "lucide-react";
import {
Component,
ComponentConfig,
@@ -8,7 +8,6 @@ import {
} from "../../../../../types/datamodel";
import { isFunctionTool } from "../../../../../types/guards";
import { MonacoEditor } from "../../../../monaco";
-import DetailGroup from "../detailgroup";
const { TextArea } = Input;
const { Option } = Select;
@@ -104,188 +103,217 @@ export const ToolFields: React.FC<ToolFieldsProps> = ({
};
return (
- <div className="space-y-6">
- <DetailGroup title="Component Details">
- <div className="space-y-4">
- <label className="block">
- <span className="text-sm font-medium text-gray-700">Name</span>
- <Input
- value={component.label || ""}
- onChange={(e) => handleComponentUpdate({ label: e.target.value })}
- placeholder="Tool name"
- className="mt-1"
- />
- </label>
-
- <label className="block">
- <span className="text-sm font-medium text-gray-700">
- Description
- </span>
- <TextArea
- value={component.description || ""}
- onChange={(e) =>
- handleComponentUpdate({ description: e.target.value })
- }
- placeholder="Tool description"
- rows={4}
- className="mt-1"
- />
- </label>
- </div>
- </DetailGroup>
+ <Collapse
+ defaultActiveKey={["details", "configuration"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "details",
+ label: (
+ <div className="flex items-center gap-2">
+ <User className="w-4 h-4 text-blue-500" />
+ <span className="font-medium">Component Details</span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ <label className="block">
+ <span className="text-sm font-medium text-gray-700">Name</span>
+ <Input
+ value={component.label || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ label: e.target.value })
+ }
+ placeholder="Tool name"
+ className="mt-1"
+ />
+ </label>
- <DetailGroup title="Configuration">
- <div className="space-y-4">
- <label className="block">
- <span className="text-sm font-medium text-gray-700">
- Function Name
- </span>
- <Input
- value={component.config.name || ""}
- onChange={(e) =>
- handleComponentUpdate({
- config: { ...component.config, name: e.target.value },
- })
- }
- placeholder="Function name"
- className="mt-1"
- />
- </label>
+ <label className="block">
+ <span className="text-sm font-medium text-gray-700">
+ Description
+ </span>
+ <TextArea
+ value={component.description || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ description: e.target.value })
+ }
+ placeholder="Tool description"
+ rows={4}
+ className="mt-1"
+ />
+ </label>
+ </div>
+ ),
+ },
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-green-500" />
+ <span className="font-medium">Tool Configuration</span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ <label className="block">
+ <span className="text-sm font-medium text-gray-700">
+ Function Name
+ </span>
+ <Input
+ value={component.config.name || ""}
+ onChange={(e) =>
+ handleComponentUpdate({
+ config: { ...component.config, name: e.target.value },
+ })
+ }
+ placeholder="Function name"
+ className="mt-1"
+ />
+ </label>
- <div className="space-y-2">
- <span className="text-sm font-medium text-gray-700">
- Global Imports
- </span>
- <div className="flex flex-wrap gap-2 mt-2">
- {(component.config.global_imports || []).map((imp, index) => (
- <div
- key={index}
- className="flex items-center gap-2 bg-tertiary rounded px-2 py-1"
- >
- <span className="text-sm">{formatImport(imp)}</span>
- <Button
- type="text"
- size="small"
- className="flex items-center justify-center h-6 w-6 p-0"
- onClick={() => handleRemoveImport(index)}
- icon={<MinusCircle className="h-4 w-4" />}
- />
+ <div className="space-y-2">
+ <span className="text-sm font-medium text-gray-700">
+ Global Imports
+ </span>
+ <div className="flex flex-wrap gap-2 mt-2">
+ {(component.config.global_imports || []).map((imp, index) => (
+ <div
+ key={index}
+ className="flex items-center gap-2 bg-tertiary rounded px-2 py-1"
+ >
+ <span className="text-sm">{formatImport(imp)}</span>
+ <Button
+ type="text"
+ size="small"
+ className="flex items-center justify-center h-6 w-6 p-0"
+ onClick={() => handleRemoveImport(index)}
+ icon={<MinusCircle className="h-4 w-4" />}
+ />
+ </div>
+ ))}
</div>
- ))}
- </div>
- {showAddImport ? (
- <div className="border rounded p-3 space-y-3">
- <Select
- value={importType}
- onChange={setImportType}
- style={{ width: 200 }}
- >
- <Option value="direct">Direct Import</Option>
- <Option value="fromModule">From Module Import</Option>
- </Select>
+ {showAddImport ? (
+ <div className="border rounded p-3 space-y-3">
+ <Select
+ value={importType}
+ onChange={setImportType}
+ style={{ width: 200 }}
+ >
+ <Option value="direct">Direct Import</Option>
+ <Option value="fromModule">From Module Import</Option>
+ </Select>
- {importType === "direct" ? (
- <Space>
- <Input
- placeholder="Package name (e.g., os)"
- className="w-64"
- value={directImport}
- onChange={(e) => setDirectImport(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && directImport) {
- handleAddImport();
- }
- }}
- />
- <Button onClick={handleAddImport} disabled={!directImport}>
- Add
- </Button>
- </Space>
+ {importType === "direct" ? (
+ <Space>
+ <Input
+ placeholder="Package name (e.g., os)"
+ className="w-64"
+ value={directImport}
+ onChange={(e) => setDirectImport(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && directImport) {
+ handleAddImport();
+ }
+ }}
+ />
+ <Button
+ onClick={handleAddImport}
+ disabled={!directImport}
+ >
+ Add
+ </Button>
+ </Space>
+ ) : (
+ <Space direction="vertical" className="w-full">
+ <Input
+ placeholder="Module name (e.g., typing)"
+ className="w-64"
+ value={moduleImport.module}
+ onChange={(e) =>
+ setModuleImport((prev) => ({
+ ...prev,
+ module: e.target.value,
+ }))
+ }
+ />
+ <Space className="w-full">
+ <Input
+ placeholder="Import names (comma-separated)"
+ className="w-64"
+ value={moduleImport.imports}
+ onChange={(e) =>
+ setModuleImport((prev) => ({
+ ...prev,
+ imports: e.target.value,
+ }))
+ }
+ />
+ <Button
+ onClick={handleAddImport}
+ disabled={
+ !moduleImport.module || !moduleImport.imports
+ }
+ >
+ Add
+ </Button>
+ </Space>
+ </Space>
+ )}
+ </div>
) : (
- <Space direction="vertical" className="w-full">
- <Input
- placeholder="Module name (e.g., typing)"
- className="w-64"
- value={moduleImport.module}
- onChange={(e) =>
- setModuleImport((prev) => ({
- ...prev,
- module: e.target.value,
- }))
- }
- />
- <Space className="w-full">
- <Input
- placeholder="Import names (comma-separated)"
- className="w-64"
- value={moduleImport.imports}
- onChange={(e) =>
- setModuleImport((prev) => ({
- ...prev,
- imports: e.target.value,
- }))
- }
- />
- <Button
- onClick={handleAddImport}
- disabled={!moduleImport.module || !moduleImport.imports}
- >
- Add
- </Button>
- </Space>
- </Space>
+ <Button
+ type="dashed"
+ onClick={() => setShowAddImport(true)}
+ className="w-full"
+ >
+ <PlusCircle className="h-4 w-4 mr-2" />
+ Add Import
+ </Button>
)}
</div>
- ) : (
- <Button
- type="dashed"
- onClick={() => setShowAddImport(true)}
- className="w-full"
- >
- <PlusCircle className="h-4 w-4 mr-2" />
- Add Import
- </Button>
- )}
- </div>
- <label className="block">
- <span className="text-sm font-medium text-gray-700">
- Source Code
- </span>
- <div className="mt-1 h-96">
- <MonacoEditor
- value={component.config.source_code || ""}
- editorRef={editorRef}
- language="python"
- onChange={(value) =>
- handleComponentUpdate({
- config: { ...component.config, source_code: value },
- })
- }
- />
- </div>
- </label>
+ <label className="block">
+ <span className="text-sm font-medium text-gray-700">
+ Source Code
+ </span>
+ <div className="mt-1 h-96">
+ <MonacoEditor
+ value={component.config.source_code || ""}
+ editorRef={editorRef}
+ language="python"
+ onChange={(value) =>
+ handleComponentUpdate({
+ config: { ...component.config, source_code: value },
+ })
+ }
+ />
+ </div>
+ </label>
- <div className="flex items-center gap-2">
- <span className="text-sm font-medium text-gray-700">
- Has Cancellation Support
- </span>
- <Switch
- checked={component.config.has_cancellation_support || false}
- onChange={(checked) =>
- handleComponentUpdate({
- config: {
- ...component.config,
- has_cancellation_support: checked,
- },
- })
- }
- />
- </div>
- </div>
- </DetailGroup>
- </div>
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-gray-700">
+ Has Cancellation Support
+ </span>
+ <Switch
+ checked={component.config.has_cancellation_support || false}
+ onChange={(checked) =>
+ handleComponentUpdate({
+ config: {
+ ...component.config,
+ has_cancellation_support: checked,
+ },
+ })
+ }
+ />
+ </div>
+ </div>
+ ),
+ },
+ ]}
+ />
);
};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/elicitation-dialog.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/elicitation-dialog.tsx
new file mode 100644
index 000000000..083dbef35
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/elicitation-dialog.tsx
@@ -0,0 +1,361 @@
+import React, { useState, useEffect } from "react";
+import {
+ Modal,
+ Button,
+ Form,
+ Input,
+ Checkbox,
+ InputNumber,
+ Select,
+ Space,
+ Typography,
+ Alert,
+ Card,
+} from "antd";
+import {
+ CheckCircle,
+ XCircle,
+ AlertTriangle,
+ MessageSquare,
+} from "lucide-react";
+import {
+ ElicitationRequest,
+ ElicitationResponse,
+} from "../../../../../../views/mcp/api";
+
+const { Title, Text, Paragraph } = Typography;
+const { Option } = Select;
+
+interface ElicitationDialogProps {
+ request: ElicitationRequest | null;
+ onResponse: (response: ElicitationResponse) => void;
+ visible: boolean;
+ onCancel: () => void;
+}
+
+interface FormFieldProps {
+ name: string;
+ schema: any;
+ value: any;
+ onChange: (name: string, value: any) => void;
+ required?: boolean;
+}
+
+const FormField: React.FC<FormFieldProps> = ({
+ name,
+ schema,
+ value,
+ onChange,
+ required = false,
+}) => {
+ const {
+ type,
+ description,
+ minimum,
+ maximum,
+ enum: enumValues,
+ } = schema || {};
+
+ const handleChange = (newValue: any) => {
+ onChange(name, newValue);
+ };
+
+ const renderField = () => {
+ switch (type) {
+ case "boolean":
+ return (
+ <Checkbox
+ checked={value || false}
+ onChange={(e) => handleChange(e.target.checked)}
+ >
+ {description || name}
+ </Checkbox>
+ );
+
+ case "number":
+ case "integer":
+ return (
+ <InputNumber
+ value={value}
+ onChange={handleChange}
+ min={minimum}
+ max={maximum}
+ placeholder={description || name}
+ style={{ width: "100%" }}
+ step={type === "integer" ? 1 : 0.1}
+ />
+ );
+
+ case "string":
+ if (enumValues && Array.isArray(enumValues)) {
+ return (
+ <Select
+ value={value}
+ onChange={handleChange}
+ placeholder={description || name}
+ style={{ width: "100%" }}
+ >
+ {enumValues.map((option: any) => (
+ <Option key={option} value={option}>
+ {option}
+ </Option>
+ ))}
+ </Select>
+ );
+ }
+ return (
+ <Input
+ value={value || ""}
+ onChange={(e) => handleChange(e.target.value)}
+ placeholder={description || name}
+ />
+ );
+
+ default:
+ return (
+ <Input
+ value={value || ""}
+ onChange={(e) => handleChange(e.target.value)}
+ placeholder={description || name}
+ />
+ );
+ }
+ };
+
+ return (
+ <Form.Item
+ label={description || name}
+ required={required}
+ style={{ marginBottom: 16 }}
+ >
+ {renderField()}
+ </Form.Item>
+ );
+};
+
+export const ElicitationDialog: React.FC<ElicitationDialogProps> = ({
+ request,
+ onResponse,
+ visible,
+ onCancel,
+}) => {
+ const [formData, setFormData] = useState<Record<string, any>>({});
+ const [isFormValid, setIsFormValid] = useState(false);
+ const [timeoutWarning, setTimeoutWarning] = useState(false);
+
+ // Reset form data when request changes
+ useEffect(() => {
+ if (request?.requestedSchema?.properties) {
+ const initialData: Record<string, any> = {};
+ Object.keys(request.requestedSchema.properties).forEach((key) => {
+ const property = request.requestedSchema.properties[key];
+ if (property.default !== undefined) {
+ initialData[key] = property.default;
+ } else if (property.type === "boolean") {
+ initialData[key] = false;
+ }
+ });
+ setFormData(initialData);
+ } else {
+ setFormData({});
+ }
+ setTimeoutWarning(false);
+ }, [request]);
+
+ // Validate form
+ useEffect(() => {
+ if (!request?.requestedSchema?.properties) {
+ setIsFormValid(true);
+ return;
+ }
+
+ const { properties, required = [] } = request.requestedSchema;
+ const isValid = required.every((fieldName: string) => {
+ const value = formData[fieldName];
+ return value !== undefined && value !== null && value !== "";
+ });
+
+ setIsFormValid(isValid);
+ }, [formData, request]);
+
+ // Show timeout warning after 25 seconds
+ useEffect(() => {
+ if (!visible) return;
+
+ const timer = setTimeout(() => {
+ setTimeoutWarning(true);
+ }, 25000);
+
+ return () => clearTimeout(timer);
+ }, [visible]);
+
+ const handleFieldChange = (name: string, value: any) => {
+ setFormData((prev) => ({
+ ...prev,
+ [name]: value,
+ }));
+ };
+
+ const handleAccept = () => {
+ if (!request) return;
+
+ const response: ElicitationResponse = {
+ type: "elicitation_response",
+ request_id: request.request_id,
+ action: "accept",
+ data: formData,
+ session_id: request.session_id,
+ };
+
+ console.log("ElicitationDialog: Sending accept response:", response);
+ onResponse(response);
+ };
+
+ const handleDecline = () => {
+ if (!request) return;
+
+ const response: ElicitationResponse = {
+ type: "elicitation_response",
+ request_id: request.request_id,
+ action: "decline",
+ session_id: request.session_id,
+ };
+
+ onResponse(response);
+ };
+
+ const handleCancel = () => {
+ if (!request) return;
+
+ const response: ElicitationResponse = {
+ type: "elicitation_response",
+ request_id: request.request_id,
+ action: "cancel",
+ session_id: request.session_id,
+ };
+
+ onResponse(response);
+ onCancel();
+ };
+
+ if (!request) return null;
+
+ const { requestedSchema } = request;
+ const properties = requestedSchema?.properties || {};
+ const required = requestedSchema?.required || [];
+
+ return (
+ <Modal
+ title={
+ <Space>
+ <MessageSquare size={20} className="text-blue-600" />
+ <span>Tool Request</span>
+ </Space>
+ }
+ open={visible}
+ onCancel={handleCancel}
+ footer={null}
+ width={600}
+ maskClosable={false}
+ destroyOnHidden
+ >
+ <Card>
+ <Space direction="vertical" style={{ width: "100%" }} size="large">
+ {/* Message */}
+ <div>
+ <Title level={4} style={{ marginBottom: 8 }}>
+ Request Details
+ </Title>
+ <Paragraph>{request.message}</Paragraph>
+ </div>
+
+ {/* Timeout Warning */}
+ {timeoutWarning && (
+ <Alert
+ message="Time Limit Warning"
+ description="This request will timeout in 5 seconds. Please respond quickly."
+ type="warning"
+ icon={<AlertTriangle size={16} />}
+ showIcon
+ />
+ )}
+
+ {/* Form Fields */}
+ {Object.keys(properties).length > 0 && (
+ <div>
+ <Title level={5} style={{ marginBottom: 16 }}>
+ Required Information
+ </Title>
+ <Form layout="vertical">
+ {Object.entries(properties).map(([fieldName, fieldSchema]) => (
+ <FormField
+ key={fieldName}
+ name={fieldName}
+ schema={fieldSchema}
+ value={formData[fieldName]}
+ onChange={handleFieldChange}
+ required={required.includes(fieldName)}
+ />
+ ))}
+ </Form>
+ </div>
+ )}
+
+ {/* Actions */}
+ <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
+ <Button onClick={handleCancel} size="large">
+ Cancel
+ </Button>
+ <Button
+ onClick={handleDecline}
+ size="large"
+ danger
+ icon={<XCircle size={16} />}
+ >
+ Decline
+ </Button>
+ <Button
+ onClick={handleAccept}
+ type="primary"
+ size="large"
+ disabled={!isFormValid}
+ icon={<CheckCircle size={16} />}
+ >
+ Accept
+ </Button>
+ </div>
+ </Space>
+ </Card>
+ </Modal>
+ );
+};
+
+// Elicitation notification badge component
+interface ElicitationBadgeProps {
+ count: number;
+ onClick?: () => void;
+}
+
+export const ElicitationBadge: React.FC<ElicitationBadgeProps> = ({
+ count,
+ onClick,
+}) => {
+ if (count === 0) return null;
+
+ return (
+ <Button
+ type="primary"
+ size="small"
+ onClick={onClick}
+ style={{
+ backgroundColor: "#f59e0b",
+ borderColor: "#f59e0b",
+ fontSize: "12px",
+ height: "24px",
+ padding: "0 8px",
+ }}
+ >
+ {count} pending
+ </Button>
+ );
+};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/index.ts b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/index.ts
new file mode 100644
index 000000000..da42d24d7
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/index.ts
@@ -0,0 +1,5 @@
+export { WorkbenchFields } from "./workbench-fields";
+export { McpCapabilitiesPanel } from "./mcp-capabilities-panel";
+export { McpToolsTab } from "./mcp-tools-tab";
+export { McpResourcesTab } from "./mcp-resources-tab";
+export { McpPromptsTab } from "./mcp-prompts-tab";
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-capabilities-panel.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-capabilities-panel.tsx
new file mode 100644
index 000000000..0fa4ff3e3
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-capabilities-panel.tsx
@@ -0,0 +1,655 @@
+import React, { useState, useCallback, useRef } from "react";
+import {
+ Button,
+ Card,
+ Segmented,
+ Alert,
+ Spin,
+ Empty,
+ Typography,
+ Space,
+ Tag,
+ Skeleton,
+ Collapse,
+ Badge,
+ Tooltip,
+} from "antd";
+import {
+ Wrench,
+ CheckCircle,
+ XCircle,
+ Settings,
+ FileText,
+ Package,
+ Info,
+ Wifi,
+ WifiOff,
+ Play,
+ Unplug,
+ Activity,
+ ChevronDown,
+ ChevronUp,
+ MessageSquare,
+} from "lucide-react";
+import { McpServerParams } from "../../../../../../types/datamodel";
+import {
+ ServerCapabilities,
+ McpWebSocketState,
+ McpWebSocketClient,
+ McpActivityMessage,
+ ElicitationRequest,
+ ElicitationResponse,
+} from "../../../../../../views/mcp/api";
+import { McpToolsTab } from "./mcp-tools-tab";
+import { McpResourcesTab } from "./mcp-resources-tab";
+import { McpPromptsTab } from "./mcp-prompts-tab";
+import { ElicitationDialog, ElicitationBadge } from "./elicitation-dialog";
+
+const { Text, Title } = Typography;
+
+interface McpCapabilitiesPanelProps {
+ serverParams: McpServerParams;
+}
+
+export const McpCapabilitiesPanel: React.FC<McpCapabilitiesPanelProps> = ({
+ serverParams,
+}) => {
+ const [wsState, setWsState] = useState<McpWebSocketState>({
+ connected: false,
+ connecting: false,
+ capabilities: null,
+ sessionId: null,
+ error: null,
+ lastActivity: null,
+ activityMessages: [],
+ pendingElicitations: [],
+ });
+ const [wsClient, setWsClient] = useState<McpWebSocketClient | null>(null);
+ const [activeTab, setActiveTab] = useState<string>("tools");
+ const [loadingContent, setLoadingContent] = useState(false);
+ const wsClientRef = useRef<McpWebSocketClient | null>(null);
+
+ // Activity stream state
+ const [activityExpanded, setActivityExpanded] = useState<string[]>([]);
+ const activityStreamRef = useRef<HTMLDivElement>(null);
+
+ // Elicitation state
+ const [currentElicitation, setCurrentElicitation] =
+ useState<ElicitationRequest | null>(null);
+ const [elicitationDialogVisible, setElicitationDialogVisible] =
+ useState(false);
+
+ const { connected, connecting, capabilities, error, pendingElicitations } =
+ wsState;
+
+ // Auto-scroll to bottom when new messages arrive
+ React.useEffect(() => {
+ if (activityStreamRef.current && wsState.activityMessages.length > 0) {
+ activityStreamRef.current.scrollTo({
+ top: activityStreamRef.current.scrollHeight,
+ behavior: "smooth",
+ });
+ }
+ }, [wsState.activityMessages]);
+
+ // Keep ref in sync with state
+ React.useEffect(() => {
+ wsClientRef.current = wsClient;
+ }, [wsClient]);
+
+ // Handle manual connection
+ const handleConnect = useCallback(async () => {
+ // Disconnect any existing client (should already be done by useEffect, but just in case)
+ if (wsClient) {
+ wsClient.disconnect();
+ }
+
+ const client = new McpWebSocketClient(
+ serverParams,
+ (stateUpdate: Partial<McpWebSocketState>) => {
+ setWsState((prev: McpWebSocketState) => {
+ const newState = { ...prev, ...stateUpdate };
+ return newState;
+ });
+ }
+ );
+
+ setWsClient(client);
+ await client.connect();
+ }, [serverParams]);
+
+ // Handle disconnect
+ const handleDisconnect = useCallback(() => {
+ if (wsClient) {
+ wsClient.disconnect();
+ setWsClient(null);
+ }
+ }, [wsClient]);
+
+ // Handle tab switching with loading state to minimize jankiness
+ const handleTabChange = useCallback((value: string) => {
+ setLoadingContent(true);
+ setActiveTab(value);
+
+ // Brief delay to show skeleton and allow content to prepare
+ setTimeout(() => {
+ setLoadingContent(false);
+ }, 150);
+ }, []);
+
+ // Reset connection and state when server parameters change
+ React.useEffect(() => {
+ // Disconnect current connection if it exists
+ const currentClient = wsClientRef.current;
+ if (currentClient) {
+ currentClient.disconnect();
+ setWsClient(null);
+ }
+
+ // Reset all state to initial values
+ setWsState({
+ connected: false,
+ connecting: false,
+ capabilities: null,
+ sessionId: null,
+ error: null,
+ lastActivity: null,
+ activityMessages: [],
+ pendingElicitations: [],
+ });
+
+ // Reset UI state
+ setActiveTab("tools");
+ setLoadingContent(false);
+ setCurrentElicitation(null);
+ setElicitationDialogVisible(false);
+ setActivityExpanded([]);
+ }, [serverParams]); // Only depends on serverParams
+
+ // Handle elicitation requests - show dialog for the first pending elicitation
+ React.useEffect(() => {
+ if (pendingElicitations.length > 0 && !currentElicitation) {
+ const firstElicitation = pendingElicitations[0];
+ setCurrentElicitation(firstElicitation);
+ setElicitationDialogVisible(true);
+ } else if (pendingElicitations.length === 0 && currentElicitation) {
+ // No more pending elicitations, close dialog
+ setCurrentElicitation(null);
+ setElicitationDialogVisible(false);
+ }
+ }, [pendingElicitations, currentElicitation]);
+
+ // Handle elicitation response
+ const handleElicitationResponse = useCallback(
+ (response: ElicitationResponse) => {
+ if (wsClient && currentElicitation) {
+ wsClient.sendElicitationResponse(response);
+
+ // Clear current elicitation and close dialog
+ setCurrentElicitation(null);
+ setElicitationDialogVisible(false);
+
+ // If there are more pending elicitations, show the next one
+ if (pendingElicitations.length > 1) {
+ // This will be handled by the useEffect that watches pendingElicitations
+ }
+ } else {
+ console.error(
+ "McpCapabilitiesPanel: Cannot send response - missing wsClient or currentElicitation"
+ );
+ }
+ },
+ [wsClient, currentElicitation, pendingElicitations]
+ );
+
+ // Handle elicitation dialog close (cancel)
+ const handleElicitationCancel = useCallback(() => {
+ if (currentElicitation) {
+ // Send a cancel response
+ const cancelResponse: ElicitationResponse = {
+ type: "elicitation_response",
+ request_id: currentElicitation.request_id,
+ action: "cancel",
+ session_id: currentElicitation.session_id,
+ };
+ handleElicitationResponse(cancelResponse);
+ }
+ }, [currentElicitation, handleElicitationResponse]);
+
+ // Cleanup effect - disconnect when component unmounts
+ React.useEffect(() => {
+ return () => {
+ console.log("Component unmounting, disconnecting WebSocket");
+ if (wsClient) {
+ wsClient.disconnect();
+ }
+ };
+ }, [wsClient]);
+
+ const renderConnectionStatus = () => {
+ if (connecting) {
+ return (
+ <div className="text-center py-8 px-4">
+ <Spin size="large" className="mb-4" />
+ <div>
+ <Text strong className="block mb-2">
+ Connecting to MCP Server
+ </Text>
+ <Text type="secondary" className="text-sm">
+ Establishing WebSocket connection and discovering capabilities...
+ </Text>
+ </div>
+ <div className="mt-4">
+ <Button
+ onClick={handleDisconnect}
+ size="small"
+ icon={<Unplug size={14} />}
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <Alert
+ message="Connection Error"
+ description={
+ <div>
+ <Text>{error}</Text>
+ {error.includes("JSON") && (
+ <div className="mt-2">
+ <Text type="secondary" className="text-xs">
+ This might indicate the AutoGen Studio server is not running
+ or the MCP routes are not properly configured.
+ </Text>
+ </div>
+ )}
+ <div className="mt-3">
+ <Space>
+ <Button
+ type="primary"
+ size="small"
+ onClick={handleConnect}
+ icon={<Wifi size={14} />}
+ >
+ Retry Connection
+ </Button>
+ <Button
+ size="small"
+ onClick={handleDisconnect}
+ icon={<Unplug size={14} />}
+ >
+ Reset
+ </Button>
+ </Space>
+ </div>
+ </div>
+ }
+ type="error"
+ showIcon
+ className="m-4"
+ />
+ );
+ }
+
+ if (!connected && !capabilities) {
+ return (
+ <div className="text-center py-8 px-4">
+ <div className="mb-6">
+ <Title level={4} className="mb-2 text-secondary">
+ MCP Server Testing Panel
+ </Title>
+ <Text
+ type="secondary"
+ className="block text-sm leading-relaxed max-w-md mx-auto"
+ >
+ Click the button below to establish a WebSocket connection and
+ discover what tools, resources, and prompts are available from
+ this MCP server.
+ </Text>
+ </div>
+ <Button
+ type="primary"
+ onClick={handleConnect}
+ icon={<Play size={16} />}
+ size="large"
+ className="rounded-md h-10 px-6 font-medium"
+ >
+ Connect to Server
+ </Button>
+ <div className="mt-4">
+ <Text type="secondary" className="text-xs">
+ Server: {serverParams.type} •{" "}
+ {(serverParams as any).command ||
+ (serverParams as any).url ||
+ "Unknown"}
+ </Text>
+ </div>
+ </div>
+ );
+ }
+
+ return null;
+ };
+
+ const renderConnectionIndicator = () => {
+ if (!connected && !connecting) {
+ return (
+ <Tag
+ color="red"
+ icon={<WifiOff className="inline-block mr-1" size={12} />}
+ >
+ Disconnected
+ </Tag>
+ );
+ }
+
+ if (connecting) {
+ return (
+ <Tag color="orange" icon={<Spin size="small" />}>
+ Connecting
+ </Tag>
+ );
+ }
+
+ return (
+ <Tag
+ color="green"
+ icon={<Wifi className="inline-block mr-1" size={12} />}
+ >
+ Connected
+ </Tag>
+ );
+ };
+
+ // Show connection status if not connected or no capabilities
+ const connectionStatus = renderConnectionStatus();
+ if (connectionStatus) {
+ return connectionStatus;
+ }
+
+ // Create segmented options based on available capabilities
+ const segmentedOptions = [];
+
+ if (capabilities?.tools) {
+ segmentedOptions.push({
+ label: (
+ <span className="flex items-center gap-1.5">
+ <Wrench size={16} />
+ <span>Tools</span>
+ </span>
+ ),
+ value: "tools",
+ });
+ }
+
+ if (capabilities?.resources) {
+ segmentedOptions.push({
+ label: (
+ <span className="flex items-center gap-1.5">
+ <Package size={16} />
+ <span>Resources</span>
+ </span>
+ ),
+ value: "resources",
+ });
+ }
+
+ if (capabilities?.prompts) {
+ segmentedOptions.push({
+ label: (
+ <span className="flex items-center gap-1.5">
+ <FileText size={16} />
+ <span>Prompts</span>
+ </span>
+ ),
+ value: "prompts",
+ });
+ }
+
+ // Render the active tab content
+ const renderActiveContent = () => {
+ if (loadingContent) {
+ return (
+ <div className="p-6">
+ <Skeleton active paragraph={{ rows: 4 }} />
+ </div>
+ );
+ }
+
+ switch (activeTab) {
+ case "tools":
+ return (
+ <McpToolsTab
+ key="tools-tab"
+ serverParams={serverParams}
+ wsClient={wsClient}
+ connected={connected}
+ capabilities={capabilities}
+ />
+ );
+ case "resources":
+ return (
+ <McpResourcesTab
+ key="resources-tab"
+ serverParams={serverParams}
+ wsClient={wsClient}
+ connected={connected}
+ capabilities={capabilities}
+ />
+ );
+ case "prompts":
+ return (
+ <McpPromptsTab
+ key="prompts-tab"
+ serverParams={serverParams}
+ wsClient={wsClient}
+ connected={connected}
+ capabilities={capabilities}
+ />
+ );
+ default:
+ return (
+ <Empty
+ description="Select a capability to explore"
+ className="py-12 px-6"
+ />
+ );
+ }
+ };
+
+ const renderActivityStream = () => {
+ const { activityMessages } = wsState;
+
+ if (!connected || activityMessages.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className="h-full flex flex-col border-l border-gray-200">
+ {/* Header */}
+ <div className="px-4 py-3 border-b border-gray-200 ">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Activity size={16} className="text-gray-600" />
+ <span className="font-medium text-sm">Notification Stream</span>
+ <Badge count={activityMessages.length} size="small" />
+ </div>
+ <Button
+ size="small"
+ type="text"
+ onClick={() =>
+ setWsState((prev) => ({ ...prev, activityMessages: [] }))
+ }
+ className="text-xs"
+ >
+ Clear
+ </Button>
+ </div>
+ </div>
+
+ {/* Messages Container */}
+ <div
+ ref={activityStreamRef}
+ className="flex-1 overflow-y-auto p-2 space-y-1"
+ >
+ {activityMessages.map((msg: McpActivityMessage) => (
+ <div
+ key={msg.id}
+ className="border bg-secondary rounded p-2 hover:bg-primary transition-colors"
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 flex-1 min-w-0">
+ <span className="text-gray-500 flex-shrink-0">
+ {msg.activity_type === "protocol" && <Activity size={14} />}
+ {msg.activity_type === "error" && <XCircle size={14} />}
+ {msg.activity_type === "sampling" && (
+ <CheckCircle size={14} />
+ )}
+ {msg.activity_type === "elicitation" && (
+ <MessageSquare size={14} />
+ )}
+ </span>
+ <Text className="text-sm truncate flex-1">{msg.message}</Text>
+ </div>
+ <Text
+ type="secondary"
+ className="text-xs whitespace-nowrap ml-2 flex-shrink-0"
+ >
+ {msg.timestamp.toLocaleTimeString()}
+ </Text>
+ </div>
+ {msg.details && (
+ <Collapse
+ ghost
+ size="small"
+ className="mt-1"
+ items={[
+ {
+ key: "1",
+ label: (
+ <Text type="secondary" className="text-xs">
+ View Details
+ </Text>
+ ),
+ children: (
+ <pre className="bg-gray-50 p-2 rounded text-xs overflow-x-auto mt-1">
+ {JSON.stringify(msg.details, null, 2)}
+ </pre>
+ ),
+ },
+ ]}
+ />
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div className="h-full flex flex-col">
+ <div>
+ <div className="flex justify-between items-center mb-3">
+ <div className="flex items-center gap-2">
+ <Title level={5} className="m-0">
+ Server Capabilities
+ </Title>
+ {pendingElicitations.length > 0 && (
+ <ElicitationBadge count={pendingElicitations.length} />
+ )}
+ </div>
+ <Space>
+ {renderConnectionIndicator()}
+ {connected && (
+ <Button
+ size="small"
+ onClick={handleDisconnect}
+ icon={<Unplug size={12} />}
+ type="text"
+ >
+ Disconnect
+ </Button>
+ )}
+ </Space>
+ </div>
+
+ {segmentedOptions.length > 0 && (
+ <Segmented
+ options={segmentedOptions}
+ value={activeTab}
+ onChange={handleTabChange}
+ className="w-full"
+ />
+ )}
+ </div>
+
+ {/* Main content area with stable layout to prevent component remounting */}
+ <div className="flex-1 overflow-hidden mt-3">
+ {/* Always use the same container structure to prevent React from unmounting components */}
+ <div
+ className="h-full grid gap-4"
+ style={{
+ gridTemplateColumns:
+ connected && wsState.activityMessages.length > 0
+ ? "1fr 400px"
+ : "1fr",
+ }}
+ >
+ {/* Main content panel */}
+ <div className="h-full overflow-auto">
+ {connected && !capabilities && !error ? (
+ <div className="text-center py-12 px-6">
+ <Spin size="large" className="mb-4" />
+ <div>
+ <Text strong className="block mb-2">
+ Discovering Server Capabilities
+ </Text>
+ <Text type="secondary" className="text-sm">
+ Retrieving available tools, resources, and prompts...
+ </Text>
+ </div>
+ </div>
+ ) : segmentedOptions.length === 0 ? (
+ <Empty
+ description={
+ <div className="text-center">
+ <Text type="secondary">
+ This MCP server doesn't expose any capabilities
+ </Text>
+ <br />
+ <Text type="secondary" className="text-xs">
+ No tools, resources, or prompts are available
+ </Text>
+ </div>
+ }
+ className="py-12 px-6"
+ />
+ ) : (
+ renderActiveContent()
+ )}
+ </div>
+
+ {/* Activity stream panel - only rendered when there are messages */}
+ {connected &&
+ wsState.activityMessages.length > 0 &&
+ renderActivityStream()}
+ </div>
+ </div>
+
+ {/* Elicitation Dialog - add this outside the main flex container */}
+ {currentElicitation && (
+ <ElicitationDialog
+ visible={elicitationDialogVisible}
+ onCancel={handleElicitationCancel}
+ request={currentElicitation}
+ onResponse={handleElicitationResponse}
+ />
+ )}
+ </div>
+ );
+};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-prompts-tab.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-prompts-tab.tsx
new file mode 100644
index 000000000..dd53d7b6c
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-prompts-tab.tsx
@@ -0,0 +1,550 @@
+import React, { useState, useCallback, useEffect, useRef } from "react";
+import { Button, Form, Input, Typography, Space, Alert, Select } from "antd";
+import {
+ FileText,
+ Eye,
+ Play,
+ RotateCcw,
+ MessageCircle,
+ User,
+ Bot,
+ Hash,
+} from "lucide-react";
+import { McpServerParams } from "../../../../../../types/datamodel";
+import { McpWebSocketClient, ServerCapabilities } from "../../../../../mcp/api";
+
+const { Text } = Typography;
+const { Option } = Select;
+
+interface Prompt {
+ name: string;
+ description?: string;
+ arguments?: Array<{
+ name: string;
+ description?: string;
+ required?: boolean;
+ }>;
+}
+
+interface PromptMessage {
+ role: "user" | "assistant";
+ content: {
+ type: "text";
+ text: string;
+ };
+}
+
+interface PromptResult {
+ name: string;
+ description?: string;
+ messages: PromptMessage[];
+}
+
+interface McpPromptsTabProps {
+ serverParams: McpServerParams;
+ wsClient: McpWebSocketClient | null;
+ connected: boolean;
+ capabilities: ServerCapabilities | null;
+}
+
+const McpPromptsTabComponent: React.FC<McpPromptsTabProps> = ({
+ serverParams,
+ wsClient,
+ connected,
+ capabilities,
+}) => {
+ const [prompts, setPrompts] = useState<Prompt[]>([]);
+ const [selectedPrompt, setSelectedPrompt] = useState<Prompt | null>(null);
+ const [promptArguments, setPromptArguments] = useState<Record<string, any>>(
+ {}
+ );
+ const [promptResult, setPromptResult] = useState<PromptResult | null>(null);
+ const [loadingPrompts, setLoadingPrompts] = useState(false);
+ const [loadingPrompt, setLoadingPrompt] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [loadingError, setLoadingError] = useState<string | null>(null);
+ const [validationErrors, setValidationErrors] = useState<
+ Record<string, string>
+ >({});
+ const promptResultRef = useRef<HTMLDivElement>(null);
+
+ const handleListPrompts = useCallback(async () => {
+ if (!connected || !wsClient) {
+ setLoadingError("WebSocket not connected");
+ return;
+ }
+
+ // Clear activity messages for this new operation
+ if (wsClient.clearActivityMessages) {
+ wsClient.clearActivityMessages();
+ }
+
+ setLoadingPrompts(true);
+ setLoadingError(null);
+
+ try {
+ const result = await wsClient.executeOperation({
+ operation: "list_prompts",
+ });
+
+ if (result?.prompts) {
+ setPrompts(result.prompts);
+ } else {
+ setLoadingError("No prompts received from server");
+ }
+ } catch (err: any) {
+ setLoadingError(
+ `Failed to fetch prompts: ${err.message || "Unknown error"}`
+ );
+ } finally {
+ setLoadingPrompts(false);
+ }
+ }, [connected]);
+
+ // Validation function for required prompt arguments
+ const validatePromptArguments = useCallback(
+ (prompt: Prompt, promptArgs: Record<string, any>): string[] => {
+ const errors: string[] = [];
+ const requiredArgs =
+ prompt.arguments?.filter((arg) => arg.required) || [];
+
+ requiredArgs.forEach((arg) => {
+ const value = promptArgs[arg.name];
+
+ // Check if required field is missing, empty, or only whitespace
+ if (
+ value === undefined ||
+ value === null ||
+ (typeof value === "string" && value.trim() === "")
+ ) {
+ errors.push(`Required argument '${arg.name}' is missing or empty`);
+ }
+ });
+
+ return errors;
+ },
+ []
+ );
+
+ // Real-time validation function
+ const validateField = useCallback(
+ (fieldName: string, value: string, isRequired: boolean): string | null => {
+ if (isRequired && (!value || value.trim() === "")) {
+ return `${fieldName} is required`;
+ }
+ return null;
+ },
+ []
+ );
+
+ // Handle argument change with validation
+ const handleArgumentChange = useCallback(
+ (argName: string, value: string, isRequired: boolean) => {
+ // Update the argument value
+ setPromptArguments((prev) => ({
+ ...prev,
+ [argName]: value,
+ }));
+
+ // Validate the field
+ const error = validateField(argName, value, isRequired);
+ setValidationErrors((prev) => ({
+ ...prev,
+ [argName]: error || "",
+ }));
+ },
+ [validateField]
+ );
+
+ const handleGetPrompt = useCallback(
+ async (prompt: Prompt) => {
+ if (!connected || !wsClient) return;
+
+ // Validate prompt arguments
+ const validationErrors = validatePromptArguments(prompt, promptArguments);
+ if (validationErrors.length > 0) {
+ setError(validationErrors.join(", "));
+ return;
+ }
+
+ // Clear activity messages for this new operation
+ if (wsClient.clearActivityMessages) {
+ wsClient.clearActivityMessages();
+ }
+
+ setLoadingPrompt(true);
+ setError(null);
+ setSelectedPrompt(prompt);
+
+ try {
+ const result = await wsClient.executeOperation({
+ operation: "get_prompt",
+ name: prompt.name,
+ arguments: promptArguments,
+ });
+
+ if (result) {
+ setPromptResult({
+ name: result.name || prompt.name,
+ description: result.description,
+ messages: result.messages || [],
+ });
+ } else {
+ setError("No prompt result received");
+ }
+ } catch (err: any) {
+ setError(`Failed to get prompt: ${err.message || "Unknown error"}`);
+ } finally {
+ setLoadingPrompt(false);
+ }
+ },
+ [connected, wsClient, promptArguments, validatePromptArguments]
+ );
+
+ // Auto-scroll to prompt result when it appears
+ useEffect(() => {
+ if (promptResult && promptResultRef.current) {
+ setTimeout(() => {
+ promptResultRef.current?.scrollIntoView({
+ behavior: "smooth",
+ block: "nearest",
+ });
+ }, 100);
+ }
+ }, [promptResult]);
+
+ // Load prompts when connected and capabilities indicate prompts are available
+ useEffect(() => {
+ if (connected && capabilities?.prompts) {
+ handleListPrompts();
+ }
+ }, [connected, capabilities?.prompts, handleListPrompts]);
+
+ // Auto-select first prompt when prompts are loaded
+ useEffect(() => {
+ if (prompts.length > 0 && !selectedPrompt) {
+ setSelectedPrompt(prompts[0]);
+ setPromptArguments({});
+ setPromptResult(null);
+ setValidationErrors({});
+ }
+ }, [prompts, selectedPrompt]);
+
+ const renderPromptsList = () => (
+ <div className="bg-secondary rounded-lg border border-tertiary p-4">
+ <div className="flex items-center gap-2 mb-4">
+ <FileText size={18} className="text-primary" />
+ <h3 className="text-lg font-semibold text-primary m-0">
+ Available Prompts
+ </h3>
+ </div>
+
+ <div className="space-y-4">
+ <Button
+ type="primary"
+ onClick={handleListPrompts}
+ loading={loadingPrompts}
+ icon={<FileText size={16} />}
+ className="flex items-center gap-2"
+ >
+ {prompts.length > 0 ? "Refresh Prompts" : "Load Prompts"}
+ </Button>
+
+ {loadingError && (
+ <Alert
+ type="error"
+ message="Failed to Load Prompts"
+ description={loadingError}
+ action={
+ <Space>
+ <Button
+ size="small"
+ onClick={handleListPrompts}
+ loading={loadingPrompts}
+ >
+ Retry
+ </Button>
+ <Button size="small" onClick={() => setLoadingError(null)}>
+ Clear
+ </Button>
+ </Space>
+ }
+ showIcon
+ />
+ )}
+
+ {prompts.length > 0 && (
+ <div className="space-y-2">
+ <Select
+ className="w-full"
+ placeholder="Select a prompt to view"
+ value={selectedPrompt?.name}
+ onChange={(promptName) => {
+ const prompt = prompts.find((p) => p.name === promptName);
+ setSelectedPrompt(prompt || null);
+ setPromptArguments({});
+ setPromptResult(null);
+ setValidationErrors({});
+ // Clear errors when selecting a new prompt to allow fresh attempts
+ setError(null);
+ }}
+ >
+ {prompts.map((prompt) => (
+ <Option
+ key={prompt.name}
+ value={prompt.name}
+ title={prompt.description}
+ >
+ <Text className="font-medium">{prompt.name}</Text>
+ </Option>
+ ))}
+ </Select>
+
+ <Text className="text-secondary text-sm">
+ Found {prompts.length} prompt(s)
+ </Text>
+ </div>
+ )}
+
+ {prompts.length === 0 && !loadingPrompts && (
+ <Text className="text-secondary text-center block py-4">
+ No prompts found
+ </Text>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderPromptForm = () => {
+ if (!selectedPrompt) return null;
+
+ const promptArgs = selectedPrompt.arguments || [];
+
+ return (
+ <div className="bg-secondary rounded-lg border border-tertiary p-4">
+ <div className="flex items-center gap-2 mb-4">
+ <MessageCircle size={18} className="text-primary" />
+ <h3 className="text-lg font-semibold text-primary m-0">
+ Configure {selectedPrompt.name}
+ </h3>
+ </div>
+
+ <div className="space-y-4">
+ {selectedPrompt.description && (
+ <Text className="text-secondary block">
+ {selectedPrompt.description}
+ </Text>
+ )}
+
+ {promptArgs.length > 0 ? (
+ <Form layout="vertical" className="space-y-4">
+ {promptArgs.map((arg) => (
+ <Form.Item
+ key={arg.name}
+ label={
+ <div className="flex items-center gap-2">
+ <Text className="font-medium text-primary">
+ {arg.name}
+ </Text>
+ {arg.required && (
+ <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-red-100 text-red-800 rounded-full">
+ Required
+ </span>
+ )}
+ </div>
+ }
+ className="mb-4"
+ >
+ <Input
+ placeholder={arg.description || `Enter ${arg.name}`}
+ value={promptArguments[arg.name] || ""}
+ onChange={(e) =>
+ handleArgumentChange(
+ arg.name,
+ e.target.value,
+ arg.required || false
+ )
+ }
+ className="w-full"
+ status={validationErrors[arg.name] ? "error" : undefined}
+ />
+ {validationErrors[arg.name] && (
+ <Text className="text-red-500 text-xs mt-1 block">
+ {validationErrors[arg.name]}
+ </Text>
+ )}
+ {arg.description && (
+ <Text className="text-secondary text-xs mt-1 block">
+ {arg.description}
+ </Text>
+ )}
+ </Form.Item>
+ ))}
+ </Form>
+ ) : (
+ <Text className="text-secondary">This prompt has no arguments</Text>
+ )}
+
+ <Button
+ type="primary"
+ icon={<Play size={16} />}
+ onClick={() => handleGetPrompt(selectedPrompt)}
+ loading={loadingPrompt}
+ className="w-full flex items-center justify-center gap-2"
+ >
+ {loadingPrompt ? "Loading..." : "Get Prompt"}
+ </Button>
+ </div>
+ </div>
+ );
+ };
+
+ const renderPromptResult = () => {
+ if (!promptResult) return null;
+
+ return (
+ <div
+ ref={promptResultRef}
+ className="bg-secondary rounded-lg border border-tertiary p-4"
+ >
+ <div className="flex items-center gap-2 mb-4">
+ <Eye size={18} className="text-primary" />
+ <h3 className="text-lg font-semibold text-primary m-0">
+ Prompt: {promptResult.name}
+ </h3>
+ </div>
+
+ <div className="space-y-4">
+ {promptResult.description && (
+ <Text className="text-secondary block">
+ {promptResult.description}
+ </Text>
+ )}
+
+ {promptResult.messages.length > 0 ? (
+ <div className="space-y-3">
+ {promptResult.messages.map((message, index) => (
+ <div
+ key={index}
+ className={`rounded-lg border-l-4 p-4 bg-tertiary`}
+ >
+ <div className="flex items-center gap-2 mb-2">
+ {message.role === "user" ? (
+ <User size={16} className="text-blue-600" />
+ ) : (
+ <Bot size={16} className="text-green-600" />
+ )}
+ <span
+ className={`inline-flex items-center px-2.5 py-1 text-sm font-medium rounded-full ${
+ message.role === "user"
+ ? "bg-blue-100 text-blue-800"
+ : "bg-green-100 text-green-800"
+ }`}
+ >
+ {message.role}
+ </span>
+ <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-gray-100 text-gray-800 rounded-full">
+ {message.content.type}
+ </span>
+ </div>
+
+ <pre className="whitespace-pre-wrap font-mono text-sm text-primary leading-relaxed">
+ {message.content.text}
+ </pre>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <Text className="text-secondary text-center block py-4">
+ No messages in this prompt
+ </Text>
+ )}
+ </div>
+ </div>
+ );
+ };
+
+ if (error) {
+ return (
+ <Alert
+ type="error"
+ message="Prompts Error"
+ description={error}
+ action={
+ <Button
+ size="small"
+ onClick={handleListPrompts}
+ loading={loadingPrompts}
+ icon={<RotateCcw size={14} />}
+ className="flex items-center gap-1"
+ >
+ Retry
+ </Button>
+ }
+ className="m-4"
+ />
+ );
+ }
+
+ return (
+ <div className="mt-4 space-y-6 h-full overflow-auto">
+ {renderPromptsList()}{" "}
+ {selectedPrompt && !loadingError && (
+ <>
+ <div className="border-t border-tertiary" />
+ {renderPromptForm()}
+ </>
+ )}
+ {error && (
+ <Alert
+ type="error"
+ message="Prompt Operation Error"
+ description={error}
+ action={
+ <Space>
+ <Button size="small" onClick={() => setError(null)}>
+ Clear Error
+ </Button>
+ {selectedPrompt && (
+ <Button
+ size="small"
+ type="primary"
+ onClick={() => handleGetPrompt(selectedPrompt)}
+ loading={loadingPrompt}
+ >
+ Retry
+ </Button>
+ )}
+ </Space>
+ }
+ showIcon
+ />
+ )}
+ {promptResult && !loadingError && (
+ <>
+ <div className="border-t border-tertiary" />
+ {renderPromptResult()}
+ </>
+ )}
+ </div>
+ );
+};
+
+// Custom comparison function to prevent unnecessary re-renders
+const arePropsEqual = (
+ prevProps: McpPromptsTabProps,
+ nextProps: McpPromptsTabProps
+): boolean => {
+ // Only re-render if connection state, capabilities, or serverParams change
+ return (
+ prevProps.connected === nextProps.connected &&
+ prevProps.capabilities === nextProps.capabilities &&
+ // Compare serverParams by JSON stringifying (deep comparison)
+ JSON.stringify(prevProps.serverParams) ===
+ JSON.stringify(nextProps.serverParams) &&
+ // Don't compare wsClient directly as it might be recreated, but compare its existence
+ !!prevProps.wsClient === !!nextProps.wsClient
+ );
+};
+
+export const McpPromptsTab = React.memo(McpPromptsTabComponent, arePropsEqual);
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-resources-tab.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-resources-tab.tsx
new file mode 100644
index 000000000..89c31a2dd
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-resources-tab.tsx
@@ -0,0 +1,379 @@
+import React, { useState, useCallback, useEffect, useRef } from "react";
+import { Button, Typography, Space, Alert, Spin } from "antd";
+import {
+ Package,
+ Eye,
+ Download,
+ RotateCcw,
+ FileText,
+ Hash,
+} from "lucide-react";
+import { McpServerParams } from "../../../../../../types/datamodel";
+import { McpWebSocketClient, ServerCapabilities } from "../../../../../mcp/api";
+
+const { Text } = Typography;
+
+interface Resource {
+ uri: string;
+ name?: string;
+ description?: string;
+ mimeType?: string;
+}
+
+interface ResourceContent {
+ type: string;
+ text?: string;
+ blob?: string;
+ mimeType?: string;
+}
+
+interface McpResourcesTabProps {
+ serverParams: McpServerParams;
+ wsClient: McpWebSocketClient | null;
+ connected: boolean;
+ capabilities: ServerCapabilities | null;
+}
+
+const McpResourcesTabComponent: React.FC<McpResourcesTabProps> = ({
+ serverParams,
+ wsClient,
+ connected,
+ capabilities,
+}) => {
+ const [resources, setResources] = useState<Resource[]>([]);
+ const [selectedResource, setSelectedResource] = useState<Resource | null>(
+ null
+ );
+ const [resourceContent, setResourceContent] = useState<
+ ResourceContent[] | null
+ >(null);
+ const [loadingResources, setLoadingResources] = useState(false);
+ const [loadingContent, setLoadingContent] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [loadingError, setLoadingError] = useState<string | null>(null);
+ const resourceContentRef = useRef<HTMLDivElement>(null);
+
+ const handleListResources = useCallback(async () => {
+ if (!connected || !wsClient) {
+ setLoadingError("WebSocket not connected");
+ return;
+ }
+
+ // Clear activity messages for this new operation
+ if (wsClient.clearActivityMessages) {
+ wsClient.clearActivityMessages();
+ }
+
+ setLoadingResources(true);
+ setLoadingError(null);
+
+ try {
+ const result = await wsClient.executeOperation({
+ operation: "list_resources",
+ });
+
+ if (result?.resources) {
+ setResources(result.resources);
+ } else {
+ setLoadingError("No resources received from server");
+ }
+ } catch (err: any) {
+ setLoadingError(
+ `Failed to fetch resources: ${err.message || "Unknown error"}`
+ );
+ } finally {
+ setLoadingResources(false);
+ }
+ }, [connected]);
+
+ const handleGetResource = useCallback(
+ async (resource: Resource) => {
+ if (!connected || !wsClient) return;
+
+ // Clear activity messages for this new operation
+ if (wsClient.clearActivityMessages) {
+ wsClient.clearActivityMessages();
+ }
+
+ setLoadingContent(true);
+ setError(null);
+ setSelectedResource(resource);
+
+ try {
+ const result = await wsClient.executeOperation({
+ operation: "read_resource",
+ uri: resource.uri,
+ });
+
+ if (result?.contents) {
+ setResourceContent(result.contents);
+ } else {
+ setError("No content received from resource");
+ }
+ } catch (err: any) {
+ setError(`Failed to get resource: ${err.message || "Unknown error"}`);
+ } finally {
+ setLoadingContent(false);
+ }
+ },
+ [connected, wsClient]
+ );
+
+ // Load resources when connected and capabilities indicate resources are available
+ useEffect(() => {
+ if (connected && capabilities?.resources) {
+ handleListResources();
+ }
+ }, [connected, capabilities?.resources, handleListResources]);
+
+ // Auto-scroll to resource content when it appears
+ useEffect(() => {
+ if (resourceContent && resourceContentRef.current) {
+ setTimeout(() => {
+ resourceContentRef.current?.scrollIntoView({
+ behavior: "smooth",
+ block: "nearest",
+ });
+ }, 100);
+ }
+ }, [resourceContent]);
+
+ const renderResourcesList = () => (
+ <div className="bg-secondary rounded-lg border border-tertiary p-4">
+ <div className="flex items-center gap-2 mb-4">
+ <Package size={18} className="text-primary" />
+ <h3 className="text-lg font-semibold text-primary m-0">
+ Available Resources
+ </h3>
+ </div>
+
+ <div className="space-y-4">
+ <Button
+ type="primary"
+ onClick={handleListResources}
+ loading={loadingResources}
+ icon={<Package size={16} />}
+ className="flex items-center gap-2"
+ >
+ {resources.length > 0 ? "Refresh Resources" : "Load Resources"}
+ </Button>
+
+ {loadingError && (
+ <Alert
+ type="error"
+ message="Failed to Load Resources"
+ description={loadingError}
+ action={
+ <Space>
+ <Button
+ size="small"
+ onClick={handleListResources}
+ loading={loadingResources}
+ >
+ Retry
+ </Button>
+ <Button size="small" onClick={() => setLoadingError(null)}>
+ Clear
+ </Button>
+ </Space>
+ }
+ showIcon
+ />
+ )}
+
+ {resources.length > 0 ? (
+ <div className="space-y-3">
+ {resources.map((resource, index) => (
+ <div
+ key={resource.uri}
+ className="bg-primary border border-tertiary rounded-md p-3 hover:border-accent transition-colors"
+ >
+ <div className="flex justify-between items-start gap-3">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-2">
+ <Text className="font-medium text-primary truncate">
+ {resource.name || resource.uri}
+ </Text>
+ {resource.mimeType && (
+ <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 rounded-full">
+ {resource.mimeType}
+ </span>
+ )}
+ </div>
+
+ {resource.description && (
+ <Text className="text-secondary text-sm mb-2 block">
+ {resource.description}
+ </Text>
+ )}
+
+ <div className="bg-tertiary rounded px-2 py-1">
+ <Text className="text-xs font-mono text-secondary break-all">
+ {resource.uri}
+ </Text>
+ </div>
+ </div>
+
+ <Button
+ type="text"
+ size="small"
+ icon={<Eye size={14} />}
+ onClick={() => handleGetResource(resource)}
+ loading={
+ loadingContent && selectedResource?.uri === resource.uri
+ }
+ className="flex items-center gap-1 text-accent hover:text-accent-dark hover:bg-accent/10"
+ >
+ View
+ </Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ !loadingResources && (
+ <Text className="text-secondary text-center block py-4">
+ No resources found
+ </Text>
+ )
+ )}
+
+ {resources.length > 0 && (
+ <Text className="text-secondary text-sm">
+ Found {resources.length} resource(s)
+ </Text>
+ )}
+ </div>
+ </div>
+ );
+
+ const renderResourceContent = () => {
+ if (!selectedResource || !resourceContent) return null;
+
+ return (
+ <div
+ ref={resourceContentRef}
+ className="bg-secondary rounded-lg border border-tertiary p-4"
+ >
+ <div className="flex items-center gap-2 mb-4">
+ <Eye size={18} className="text-primary" />
+ <h3 className="text-lg font-semibold text-primary m-0">
+ Resource Content: {selectedResource.name || selectedResource.uri}
+ </h3>
+ </div>
+
+ <div className="space-y-4">
+ {resourceContent.map((content, index) => (
+ <div
+ key={index}
+ className="bg-primary border border-tertiary rounded-lg p-4"
+ >
+ <div className="flex items-center gap-2 mb-3">
+ <span className="inline-flex items-center px-2.5 py-1 text-sm font-medium bg-green-100 text-green-800 rounded-full">
+ {content.type}
+ </span>
+ {content.mimeType && (
+ <span className="inline-flex items-center px-2.5 py-1 text-sm font-medium bg-blue-100 text-blue-800 rounded-full">
+ {content.mimeType}
+ </span>
+ )}
+ </div>
+
+ {content.text && (
+ <div>
+ <div className="flex items-center gap-2 mb-2">
+ <FileText size={16} className="text-primary" />
+ <Text className="font-medium text-primary">Content:</Text>
+ </div>
+ <pre className="whitespace-pre-wrap bg-tertiary border border-tertiary rounded-md p-3 text-sm text-primary overflow-auto max-h-96 font-mono">
+ {content.text}
+ </pre>
+ </div>
+ )}
+
+ {content.blob && (
+ <div>
+ <div className="flex items-center gap-2 mb-2">
+ <Download size={16} className="text-primary" />
+ <Text className="font-medium text-primary">
+ Binary Data:
+ </Text>
+ </div>
+ <div className="bg-tertiary border border-tertiary rounded-md p-3">
+ <div className="flex items-center gap-2 text-secondary">
+ <Download size={16} />
+ <Text className="text-secondary">
+ Binary content ({content.blob.length} characters)
+ </Text>
+ {content.mimeType?.startsWith("image/") && (
+ <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-orange-100 text-orange-800 rounded-full ml-2">
+ Image
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div className="mt-4 space-y-6 h-full overflow-auto">
+ {renderResourcesList()}
+ {selectedResource && resourceContent && !loadingError && (
+ <>
+ <div className="border-t border-tertiary" />
+ {renderResourceContent()}
+ </>
+ )}
+ {error && (
+ <Alert
+ type="error"
+ message="Resource Operation Error"
+ description={error}
+ action={
+ <Space>
+ <Button size="small" onClick={() => setError(null)}>
+ Clear Error
+ </Button>
+ <Button
+ size="small"
+ onClick={handleListResources}
+ loading={loadingResources}
+ >
+ Retry
+ </Button>
+ </Space>
+ }
+ showIcon
+ />
+ )}
+ </div>
+ );
+};
+
+// Custom comparison function to prevent unnecessary re-renders
+const arePropsEqual = (
+ prevProps: McpResourcesTabProps,
+ nextProps: McpResourcesTabProps
+): boolean => {
+ // Only re-render if connection state, capabilities, or serverParams change
+ return (
+ prevProps.connected === nextProps.connected &&
+ prevProps.capabilities === nextProps.capabilities &&
+ // Compare serverParams by JSON stringifying (deep comparison)
+ JSON.stringify(prevProps.serverParams) ===
+ JSON.stringify(nextProps.serverParams) &&
+ // Don't compare wsClient directly as it might be recreated, but compare its existence
+ !!prevProps.wsClient === !!nextProps.wsClient
+ );
+};
+
+export const McpResourcesTab = React.memo(
+ McpResourcesTabComponent,
+ arePropsEqual
+);
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-tools-tab.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-tools-tab.tsx
new file mode 100644
index 000000000..f96b96e3c
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/mcp-tools-tab.tsx
@@ -0,0 +1,917 @@
+import React, { useState, useCallback, useEffect, useRef } from "react";
+import {
+ Button,
+ Form,
+ Input,
+ Typography,
+ Space,
+ Alert,
+ Tag,
+ Spin,
+ Card,
+ Select,
+ Divider,
+ Dropdown,
+ MenuProps,
+ Image,
+ Collapse,
+} from "antd";
+import {
+ PlayCircle,
+ Wrench,
+ CheckCircle,
+ Search,
+ ChevronDown,
+ Shield,
+ AlertTriangle,
+ RotateCcw,
+ Globe,
+ Hash,
+ FileText,
+ Image as ImageIcon,
+ Code,
+ Eye,
+ EyeOff,
+} from "lucide-react";
+import { McpServerParams } from "../../../../../../types/datamodel";
+import {
+ Tool,
+ CallToolResult,
+ McpWebSocketClient,
+ ServerCapabilities,
+} from "../../../../../mcp/api";
+
+const { TextArea } = Input;
+const { Text } = Typography;
+const { Option } = Select;
+
+interface McpToolsTabProps {
+ serverParams: McpServerParams;
+ wsClient: McpWebSocketClient | null;
+ connected: boolean;
+ capabilities: ServerCapabilities | null;
+}
+
+const McpToolsTabComponent: React.FC<McpToolsTabProps> = ({
+ serverParams,
+ wsClient,
+ connected,
+ capabilities,
+}) => {
+ const [tools, setTools] = useState<Tool[]>([]);
+ const [selectedTool, setSelectedTool] = useState<Tool | null>(null);
+ const [toolArguments, setToolArguments] = useState<Record<string, any>>({});
+ const [loadingTools, setLoadingTools] = useState(false);
+ const [executingTool, setExecutingTool] = useState(false);
+ const [toolResult, setToolResult] = useState<CallToolResult | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [loadingError, setLoadingError] = useState<string | null>(null);
+ const [searchQuery, setSearchQuery] = useState<string>("");
+ const [resultView, setResultView] = useState<"raw" | "parsed">("parsed");
+ const runToolRef = useRef<HTMLDivElement>(null);
+ const toolResultRef = useRef<HTMLDivElement>(null);
+
+ // Auto-select first tool when tools are loaded
+ useEffect(() => {
+ if (tools.length > 0 && !selectedTool) {
+ const firstTool = tools[0];
+ setSelectedTool(firstTool);
+ setToolResult(null);
+
+ // Initialize tool arguments with default values based on schema
+ const initialArgs: Record<string, any> = {};
+ const schema = firstTool.inputSchema;
+ const properties = schema?.properties || {};
+
+ Object.entries(properties).forEach(([key, propSchema]: [string, any]) => {
+ if (propSchema.default !== undefined) {
+ initialArgs[key] = propSchema.default;
+ }
+ });
+
+ setToolArguments(initialArgs);
+ }
+ }, [tools, selectedTool]);
+
+ // Auto-scroll to run tool when arguments form is shown
+ useEffect(() => {
+ if (selectedTool && runToolRef.current) {
+ setTimeout(() => {
+ runToolRef.current?.scrollIntoView({
+ behavior: "smooth",
+ block: "nearest",
+ });
+ }, 100);
+ }
+ }, [selectedTool]);
+
+ // Auto-scroll to tool result when it appears
+ useEffect(() => {
+ if (toolResult && toolResultRef.current) {
+ setTimeout(() => {
+ toolResultRef.current?.scrollIntoView({
+ behavior: "smooth",
+ block: "nearest",
+ });
+ }, 100);
+ }
+ }, [toolResult]);
+
+ const handleListTools = useCallback(
+ async (clearResults: boolean = false) => {
+ if (!connected) {
+ setLoadingError("WebSocket not connected");
+ return;
+ }
+
+ if (!wsClient) {
+ setLoadingError("WebSocket client not initialized");
+ return;
+ }
+
+ setLoadingTools(true);
+ setLoadingError(null);
+
+ // Only clear selected tool and results when explicitly requested (e.g., reconnection)
+ if (clearResults) {
+ setSelectedTool(null);
+ setToolResult(null);
+ setToolArguments({});
+ }
+
+ try {
+ const result = await wsClient.executeOperation({
+ operation: "list_tools",
+ });
+
+ if (result?.tools) {
+ setTools(result.tools);
+ } else {
+ setLoadingError("No tools received from server");
+ }
+ } catch (err: any) {
+ setLoadingError(`Failed to fetch tools: ${err.message}`);
+ } finally {
+ setLoadingTools(false);
+ }
+ },
+ [connected]
+ );
+
+ // Wrapper for UI button clicks that should clear results
+ const handleRefreshTools = useCallback(() => {
+ handleListTools(true);
+ }, [handleListTools]);
+
+ // Load tools when connected and capabilities indicate tools are available
+ // Use a ref to track if we've already loaded tools to prevent unnecessary reloads
+ const hasLoadedToolsRef = useRef(false);
+
+ useEffect(() => {
+ console.log(
+ "Tools useEffect triggered - connected:",
+ connected,
+ "capabilities?.tools:",
+ !!capabilities?.tools,
+ "wsClient:",
+ !!wsClient,
+ "hasLoaded:",
+ hasLoadedToolsRef.current
+ );
+
+ if (
+ connected &&
+ capabilities?.tools &&
+ wsClient &&
+ !hasLoadedToolsRef.current
+ ) {
+ console.log("Loading tools for the first time");
+ hasLoadedToolsRef.current = true;
+ handleListTools();
+ } else if (!connected || !capabilities?.tools) {
+ // Reset the flag when disconnected or tools capability is removed
+ console.log(
+ "Resetting hasLoadedToolsRef due to disconnection or no tools capability"
+ );
+ hasLoadedToolsRef.current = false;
+ }
+ }, [connected, capabilities?.tools, handleListTools]);
+
+ const handleExecuteTool = useCallback(async () => {
+ if (!selectedTool || !connected || !wsClient) return;
+
+ // Clear activity messages for this new operation
+ if (wsClient.clearActivityMessages) {
+ wsClient.clearActivityMessages();
+ }
+
+ setExecutingTool(true);
+ setError(null);
+ setToolResult(null);
+
+ try {
+ const result = await wsClient.executeOperation({
+ operation: "call_tool",
+ tool_name: selectedTool.name,
+ arguments: toolArguments,
+ });
+
+ if (result?.result) {
+ setToolResult(result.result);
+ } else {
+ setError("No result received from tool execution");
+ }
+ } catch (err: any) {
+ setError(`Failed to execute tool: ${err.message}`);
+ } finally {
+ setExecutingTool(false);
+ }
+ }, [connected, selectedTool, toolArguments, wsClient]);
+
+ // Filter tools based on search query
+ const filteredTools = tools.filter((tool) => {
+ if (!searchQuery) return true;
+ const query = searchQuery.toLowerCase();
+ const displayName = (tool.annotations?.title || tool.name).toLowerCase();
+ const description = (tool.description || "").toLowerCase();
+ return displayName.includes(query) || description.includes(query);
+ });
+
+ // Helper function to get tool display name
+ const getToolDisplayName = (tool: Tool): string => {
+ return tool.annotations?.title || tool.name;
+ };
+
+ // Helper function to get parameter count
+ const getParameterCount = (tool: Tool): number => {
+ return Object.keys(tool.inputSchema?.properties || {}).length;
+ };
+
+ // Handle tool selection from dropdown
+ const handleMenuClick: MenuProps["onClick"] = (e) => {
+ const toolName = e.key;
+ const tool = tools.find((t) => t.name === toolName);
+ if (tool) {
+ handleToolSelect(tool);
+ }
+ };
+
+ // Handle tool selection
+ const handleToolSelect = (tool: Tool) => {
+ setSelectedTool(tool);
+ setToolResult(null);
+
+ // Initialize tool arguments with default values based on schema
+ const initialArgs: Record<string, any> = {};
+ const schema = tool.inputSchema;
+ const properties = schema?.properties || {};
+
+ Object.entries(properties).forEach(([key, propSchema]: [string, any]) => {
+ if (propSchema.default !== undefined) {
+ initialArgs[key] = propSchema.default;
+ }
+ });
+
+ setToolArguments(initialArgs);
+ };
+
+ // Render MCP result content based on MIME type
+ const renderMCPResult = (content: any, index: number) => {
+ const { type, text, data, mimeType } = content;
+
+ // Helper function to check if data is base64 encoded
+ const isBase64 = (str: string) => {
+ try {
+ return btoa(atob(str)) === str;
+ } catch (err) {
+ return false;
+ }
+ };
+
+ // Helper function to format JSON
+ const formatJSON = (jsonString: string) => {
+ try {
+ const parsed = JSON.parse(jsonString);
+ return JSON.stringify(parsed, null, 2);
+ } catch {
+ return jsonString;
+ }
+ };
+
+ // Render based on MIME type
+ const renderContent = () => {
+ // Handle images
+ if (mimeType?.startsWith("image/")) {
+ if (data && isBase64(data)) {
+ return (
+ <div>
+ <div className="flex items-center gap-2 mb-2">
+ <ImageIcon size={16} />
+ <Text strong>Image</Text>
+ <Tag color="green">{mimeType}</Tag>
+ </div>
+ <Image
+ src={`data:${mimeType};base64,${data}`}
+ alt="MCP Result Image"
+ style={{ maxWidth: "300px", maxHeight: "300px" }}
+ placeholder={<div>Loading image...</div>}
+ />
+ </div>
+ );
+ }
+ }
+
+ // Handle JSON content
+ if (
+ mimeType === "application/json" ||
+ (type === "text" &&
+ text &&
+ (text.trim().startsWith("{") || text.trim().startsWith("[")))
+ ) {
+ const jsonContent = text || data;
+ const formattedJson = formatJSON(jsonContent);
+
+ return (
+ <div>
+ <div className="flex items-center gap-2 mb-2">
+ <Code size={16} />
+ <Text strong>JSON Data</Text>
+ <Tag color="purple">application/json</Tag>
+ </div>
+ <Collapse size="small" ghost defaultActiveKey={["json"]}>
+ <Collapse.Panel
+ header={
+ <div className="flex items-center gap-2">
+ <Text type="secondary">View formatted JSON</Text>
+ </div>
+ }
+ key="json"
+ >
+ <pre
+ className="bg-secondary text-primary"
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ fontSize: "12px",
+ lineHeight: "1.4",
+ overflow: "auto",
+ maxHeight: "300px",
+ whiteSpace: "pre-wrap",
+ wordBreak: "break-word",
+ overflowWrap: "break-word",
+ margin: 0,
+ border: "1px solid var(--border-color, #e1e4e8)",
+ }}
+ >
+ {formattedJson}
+ </pre>
+ </Collapse.Panel>
+ </Collapse>
+ </div>
+ );
+ }
+
+ // Handle text content
+ if (type === "text") {
+ const textContent = text || data || "";
+ return (
+ <div>
+ <div className="flex items-center gap-2 mb-2">
+ <FileText size={16} />
+ <Text strong>Text Content</Text>
+ {mimeType && <Tag color="blue">{mimeType}</Tag>}
+ </div>
+ {textContent ? (
+ <pre
+ className="bg-secondary text-primary"
+ style={{
+ whiteSpace: "pre-wrap",
+ wordBreak: "break-word",
+ padding: "12px",
+ borderRadius: "6px",
+ fontSize: "13px",
+ lineHeight: "1.5",
+ maxHeight: "400px",
+ overflow: "auto",
+ margin: 0,
+ }}
+ >
+ {textContent}
+ </pre>
+ ) : (
+ <Text type="secondary" className="italic">
+ Empty text content
+ </Text>
+ )}
+ </div>
+ );
+ }
+
+ // Handle binary/data content
+ if (data) {
+ const dataPreview =
+ data.length > 100 ? `${data.substring(0, 100)}...` : data;
+
+ return (
+ <div>
+ <div className="flex items-center gap-2 mb-2">
+ <Code size={16} />
+ <Text strong>Binary Data</Text>
+ {mimeType && <Tag color="orange">{mimeType}</Tag>}
+ <Tag color="default">{data.length} bytes</Tag>
+ </div>
+ <Collapse size="small" ghost>
+ <Collapse.Panel
+ header={
+ <div className="flex items-center gap-2">
+ <Eye size={14} />
+ <Text type="secondary">View raw data (preview)</Text>
+ </div>
+ }
+ key="data"
+ >
+ <pre
+ className="bg-secondary text-primary"
+ style={{
+ padding: "12px",
+ borderRadius: "6px",
+ fontSize: "11px",
+ lineHeight: "1.4",
+ overflow: "auto",
+ maxHeight: "200px",
+ border: "1px solid var(--border-color, #e1e4e8)",
+ fontFamily: "monospace",
+ wordBreak: "break-all",
+ }}
+ >
+ {dataPreview}
+ </pre>
+ </Collapse.Panel>
+ </Collapse>
+ </div>
+ );
+ }
+
+ // Fallback for unknown content types
+ return (
+ <div>
+ <div className="flex items-center gap-2 mb-2">
+ <AlertTriangle size={16} />
+ <Text strong>Unknown Content</Text>
+ <Tag color="default">{type}</Tag>
+ {mimeType && <Tag color="gray">{mimeType}</Tag>}
+ </div>
+ <Text type="secondary">
+ No suitable renderer found for this content type.
+ </Text>
+ </div>
+ );
+ };
+
+ return (
+ <Card
+ key={index}
+ size="small"
+ className="bg-secondary"
+ style={{
+ border: "1px solid var(--border-color, #e8e8e8)",
+ }}
+ >
+ {renderContent()}
+ </Card>
+ );
+ };
+
+ const renderToolSelector = () => {
+ if (loadingTools) {
+ return (
+ <Card size="small" title="Available Tools">
+ <div style={{ textAlign: "center", padding: "24px" }}>
+ <Spin size="large" />
+ <div style={{ marginTop: "16px" }}>
+ <Text>Loading tools...</Text>
+ </div>
+ </div>
+ </Card>
+ );
+ }
+
+ if (tools.length === 0) {
+ return (
+ <Card size="small" title="Available Tools">
+ <Space direction="vertical" style={{ width: "100%" }}>
+ <Button
+ type="primary"
+ onClick={handleRefreshTools}
+ icon={<Wrench size={16} />}
+ >
+ Load Tools
+ </Button>
+
+ {loadingError && (
+ <Alert
+ type="error"
+ message="Failed to Load Tools"
+ description={loadingError}
+ action={
+ <Space>
+ <Button
+ size="small"
+ onClick={handleRefreshTools}
+ loading={loadingTools}
+ >
+ Retry
+ </Button>
+ <Button size="small" onClick={() => setLoadingError(null)}>
+ Clear
+ </Button>
+ </Space>
+ }
+ showIcon
+ />
+ )}
+ </Space>
+ </Card>
+ );
+ }
+
+ // Create dropdown menu items
+ const items: MenuProps["items"] = [
+ {
+ type: "group",
+ label: (
+ <div>
+ <div className="text-xs text-secondary mb-1">Select a tool</div>
+ <Input
+ prefix={<Search className="w-4 h-4" />}
+ placeholder="Search tools..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ onClick={(e) => e.stopPropagation()}
+ />
+ </div>
+ ),
+ key: "search-tools",
+ },
+ {
+ type: "divider",
+ },
+ ...filteredTools.map((tool) => {
+ const displayName = getToolDisplayName(tool);
+ const paramCount = getParameterCount(tool);
+ const truncatedDescription =
+ tool.description && tool.description.length > 50
+ ? `${tool.description.substring(0, 50)}...`
+ : tool.description || "No description available";
+
+ return {
+ label: (
+ <div>
+ <div className="flex items-center justify-between">
+ <span className="font-medium">{displayName}</span>
+ <div className="flex items-center gap-1 text-xs text-secondary">
+ <Hash size={12} />
+ <span>{paramCount}</span>
+ </div>
+ </div>
+ <div className="text-xs text-secondary mt-1">
+ {truncatedDescription}
+ </div>
+ </div>
+ ),
+ key: tool.name,
+ icon: <Wrench className="w-4 h-4" />,
+ };
+ }),
+ ];
+
+ const menuProps = {
+ items,
+ onClick: handleMenuClick,
+ };
+
+ return (
+ <Card
+ size="small"
+ title={
+ <Space style={{ width: "100%", justifyContent: "space-between" }}>
+ <span>Available Tools ({tools.length})</span>
+ <Button
+ type="link"
+ size="small"
+ onClick={handleRefreshTools}
+ loading={loadingTools}
+ icon={<Wrench size={12} />}
+ >
+ Refresh
+ </Button>
+ </Space>
+ }
+ >
+ <Space direction="vertical" style={{ width: "100%" }} size="middle">
+ <Dropdown.Button
+ menu={menuProps}
+ type="default"
+ className="w-full"
+ placement="bottomLeft"
+ icon={<ChevronDown className="w-4 h-4" />}
+ disabled={loadingTools}
+ >
+ <div className="flex items-center gap-2">
+ <Wrench className="w-4 h-4" />
+ <span>
+ {selectedTool
+ ? getToolDisplayName(selectedTool)
+ : "Select a tool"}
+ </span>
+ </div>
+ </Dropdown.Button>
+
+ {selectedTool && (
+ <div className="p-3 bg-secondary rounded border">
+ <div className="flex items-center gap-2 mb-2">
+ <Wrench size={16} />
+ <Text strong>{getToolDisplayName(selectedTool)}</Text>
+ <Tag color="blue">{getParameterCount(selectedTool)} params</Tag>
+ </div>
+ {/* Annotations on their own line, inline and wrapping if needed */}
+ <div className="flex flex-wrap gap-1 mb-2">
+ {selectedTool.annotations?.readOnlyHint && (
+ <div className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-green-50 text-green-700 border border-green-200">
+ Read-only
+ </div>
+ )}
+ {selectedTool.annotations?.destructiveHint && (
+ <div className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-red-50 text-red-700 border border-red-200">
+ Destructive
+ </div>
+ )}
+ {selectedTool.annotations?.idempotentHint && (
+ <div className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-purple-50 text-purple-700 border border-purple-200">
+ Idempotent
+ </div>
+ )}
+ {selectedTool.annotations?.openWorldHint && (
+ <div className="inline-flex items-center px-2 py-0.5 rounded-full text-xs bg-orange-50 text-orange-700 border border-orange-200">
+ Open-world
+ </div>
+ )}
+ </div>
+ {selectedTool.description && (
+ <Text type="secondary" className="text-sm">
+ {selectedTool.description}
+ </Text>
+ )}
+ </div>
+ )}
+ </Space>
+ </Card>
+ );
+ };
+
+ const renderArgumentsForm = () => {
+ if (!selectedTool) return null;
+
+ const schema = selectedTool.inputSchema;
+ const properties = schema?.properties || {};
+ const required = schema?.required || [];
+
+ return (
+ <Card size="small" title={`Run ${selectedTool.name} Tool`}>
+ <Space direction="vertical" style={{ width: "100%" }}>
+ {selectedTool.description && (
+ <Text type="secondary">{selectedTool.description}</Text>
+ )}
+
+ <Form layout="vertical">
+ {Object.entries(properties).map(
+ ([key, propSchema]: [string, any]) => (
+ <Form.Item
+ key={key}
+ label={
+ <Space>
+ <Text>{key}</Text>
+ {required.includes(key) && (
+ <Tag color="red">Required</Tag>
+ )}
+ </Space>
+ }
+ >
+ {propSchema.type === "string" && propSchema.enum ? (
+ <Select
+ style={{ width: "100%" }}
+ placeholder={`Select ${key}`}
+ value={toolArguments[key]}
+ onChange={(value) =>
+ setToolArguments({ ...toolArguments, [key]: value })
+ }
+ >
+ {propSchema.enum.map((option: string) => (
+ <Option key={option} value={option}>
+ {option}
+ </Option>
+ ))}
+ </Select>
+ ) : propSchema.type === "object" ||
+ propSchema.type === "array" ? (
+ <TextArea
+ placeholder={`Enter ${key} as JSON`}
+ rows={3}
+ value={
+ toolArguments[key]
+ ? JSON.stringify(toolArguments[key], null, 2)
+ : ""
+ }
+ onChange={(e) => {
+ try {
+ const parsed = JSON.parse(e.target.value);
+ setToolArguments({ ...toolArguments, [key]: parsed });
+ } catch {
+ // Keep the raw string for now, user might still be typing
+ setToolArguments({
+ ...toolArguments,
+ [key]: e.target.value,
+ });
+ }
+ }}
+ />
+ ) : propSchema.type === "boolean" ? (
+ <Select
+ style={{ width: "100%" }}
+ placeholder={`Select ${key}`}
+ value={toolArguments[key]}
+ onChange={(value) =>
+ setToolArguments({ ...toolArguments, [key]: value })
+ }
+ >
+ <Option value={true}>True</Option>
+ <Option value={false}>False</Option>
+ </Select>
+ ) : (
+ <Input
+ type={
+ propSchema.type === "number" ||
+ propSchema.type === "integer"
+ ? "number"
+ : "text"
+ }
+ placeholder={propSchema.description || `Enter ${key}`}
+ value={toolArguments[key] || ""}
+ onChange={(e) => {
+ let value: any = e.target.value;
+
+ // Convert to appropriate type based on schema
+ if (propSchema.type === "integer") {
+ if (value === "") {
+ value = undefined;
+ } else {
+ const intValue = parseInt(value, 10);
+ value = isNaN(intValue) ? value : intValue; // Keep as string if invalid
+ }
+ } else if (propSchema.type === "number") {
+ if (value === "") {
+ value = undefined;
+ } else {
+ const floatValue = parseFloat(value);
+ value = isNaN(floatValue) ? value : floatValue; // Keep as string if invalid
+ }
+ }
+ // Keep strings as-is, booleans are handled separately
+
+ setToolArguments({
+ ...toolArguments,
+ [key]: value,
+ });
+ }}
+ />
+ )}
+ {propSchema.description && (
+ <Text type="secondary" style={{ fontSize: "12px" }}>
+ {propSchema.description}
+ </Text>
+ )}
+ {(propSchema.type === "integer" ||
+ propSchema.type === "number") && (
+ <Text
+ type="secondary"
+ style={{ fontSize: "11px", fontStyle: "italic" }}
+ >
+ Expected: {propSchema.type} | Current:{" "}
+ {typeof toolArguments[key]} | Value:{" "}
+ {JSON.stringify(toolArguments[key])}
+ </Text>
+ )}
+ </Form.Item>
+ )
+ )}
+ </Form>
+
+ <div ref={runToolRef}>
+ <Button
+ type="primary"
+ icon={<PlayCircle size={16} />}
+ onClick={handleExecuteTool}
+ loading={executingTool}
+ style={{ width: "100%" }}
+ >
+ {executingTool ? "Executing..." : "Run Tool"}
+ </Button>
+ </div>
+ </Space>
+ </Card>
+ );
+ };
+
+ const renderToolResult = () => {
+ if (!toolResult) return null;
+
+ return (
+ <Card
+ size="small"
+ className="bg-secondary"
+ title={
+ <Space>
+ <CheckCircle size={16} color="green" />
+ Tool Result
+ <Tag color="green">
+ {toolResult.content.length} item
+ {toolResult.content.length !== 1 ? "s" : ""}
+ </Tag>
+ </Space>
+ }
+ >
+ <div ref={toolResultRef}>
+ <Space direction="vertical" style={{ width: "100%" }}>
+ {toolResult.content.map((content, index) =>
+ renderMCPResult(content, index)
+ )}
+ </Space>
+ </div>
+ </Card>
+ );
+ };
+
+ return (
+ <div style={{ width: "100%", maxWidth: "100%", overflow: "hidden" }}>
+ <Space direction="vertical" style={{ width: "100%" }}>
+ {renderToolSelector()}
+ {selectedTool && !loadingTools && !loadingError && (
+ <>
+ <Divider />
+ {renderArgumentsForm()}
+ </>
+ )}
+ {error && (
+ <Alert
+ type="error"
+ message="Tool Operation Error"
+ description={error}
+ action={
+ <Space>
+ <Button size="small" onClick={() => setError(null)}>
+ Clear Error
+ </Button>
+ {selectedTool && (
+ <Button
+ size="small"
+ type="primary"
+ onClick={handleExecuteTool}
+ loading={executingTool}
+ >
+ Retry
+ </Button>
+ )}
+ </Space>
+ }
+ showIcon
+ />
+ )}
+ {toolResult && !loadingTools && !loadingError && (
+ <>
+ <Divider />
+ {renderToolResult()}
+ </>
+ )}
+ </Space>
+ </div>
+ );
+};
+
+// Custom comparison function to prevent unnecessary re-renders
+const arePropsEqual = (
+ prevProps: McpToolsTabProps,
+ nextProps: McpToolsTabProps
+): boolean => {
+ // Only re-render if connection state, capabilities, or serverParams change
+ return (
+ prevProps.connected === nextProps.connected &&
+ prevProps.capabilities === nextProps.capabilities &&
+ // Compare serverParams by JSON stringifying (deep comparison)
+ JSON.stringify(prevProps.serverParams) ===
+ JSON.stringify(nextProps.serverParams) &&
+ // Don't compare wsClient directly as it might be recreated, but compare its existence
+ !!prevProps.wsClient === !!nextProps.wsClient
+ );
+};
+
+export const McpToolsTab = React.memo(McpToolsTabComponent, arePropsEqual);
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/tool-card.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/tool-card.tsx
new file mode 100644
index 000000000..b2fe2a2f2
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/tool-card.tsx
@@ -0,0 +1,224 @@
+import React from "react";
+import { Button, Typography } from "antd";
+import {
+ Wrench,
+ ChevronUp,
+ Info,
+ Hash,
+ Shield,
+ AlertTriangle,
+ RotateCcw,
+ Globe,
+} from "lucide-react";
+import { Tool } from "../../../../../mcp/api";
+
+const { Text } = Typography;
+
+interface ToolCardProps {
+ tool: Tool;
+ isSelected: boolean;
+ isExpanded: boolean;
+ onSelect: (tool: Tool) => void;
+ onToggleExpansion: (toolName: string) => void;
+}
+
+export const ToolCard: React.FC<ToolCardProps> = ({
+ tool,
+ isSelected,
+ isExpanded,
+ onSelect,
+ onToggleExpansion,
+}) => {
+ // Helper function to get tool display name following MCP precedence rules
+ const getToolDisplayName = (tool: Tool): string => {
+ return tool.annotations?.title || tool.name;
+ };
+
+ // Helper function to get annotation badges
+ const getAnnotationBadges = (tool: Tool) => {
+ const badges = [];
+ const annotations = tool.annotations;
+
+ if (annotations?.readOnlyHint) {
+ badges.push({
+ key: "readonly",
+ icon: <Shield size={12} />,
+ label: "Read-only",
+ color: "text-green-600 bg-green-50 border-green-200",
+ });
+ }
+ if (annotations?.destructiveHint) {
+ badges.push({
+ key: "destructive",
+ icon: <AlertTriangle size={12} />,
+ label: "Destructive",
+ color: "text-red-600 bg-red-50 border-red-200",
+ });
+ }
+ if (annotations?.idempotentHint) {
+ badges.push({
+ key: "idempotent",
+ icon: <RotateCcw size={12} />,
+ label: "Safe to retry",
+ color: "text-blue-600 bg-blue-50 border-blue-200",
+ });
+ }
+ if (annotations?.openWorldHint) {
+ badges.push({
+ key: "openworld",
+ icon: <Globe size={12} />,
+ label: "Open World",
+ color: "text-purple-600 bg-purple-50 border-purple-200",
+ });
+ }
+
+ return badges;
+ };
+
+ // Get parameter count for a tool
+ const getParameterCount = (tool: Tool): number => {
+ return Object.keys(tool.inputSchema?.properties || {}).length;
+ };
+
+ const displayName = getToolDisplayName(tool);
+ const badges = getAnnotationBadges(tool);
+ const paramCount = getParameterCount(tool);
+
+ // Better description truncation for compact cards
+ const maxDescLength = isExpanded ? 150 : 35;
+ const truncatedDescription =
+ tool.description && tool.description.length > maxDescLength
+ ? `${tool.description.substring(0, maxDescLength)}...`
+ : tool.description || "No description available";
+
+ return (
+ <div className="min-w-60 max-w-70 flex-shrink-0">
+ <div
+ onClick={() => onSelect(tool)}
+ className={`
+ cursor-pointer rounded-lg border-2 transition-all duration-200 ease-in-out
+ p-2.5 flex flex-col bg-white hover:shadow-md
+ ${isExpanded ? "h-auto" : "h-[90px]"}
+ ${
+ isSelected
+ ? "border-blue-500 shadow-lg shadow-blue-100"
+ : "border-gray-300 shadow-sm"
+ }
+ `}
+ >
+ {/* Card Header */}
+ <div className="flex items-start justify-between mb-1.5 min-h-[18px]">
+ <div className="flex items-center gap-1.5 flex-1 overflow-hidden">
+ <Wrench
+ size={12}
+ className={`flex-shrink-0 ${
+ isSelected ? "text-blue-500" : "text-gray-500"
+ }`}
+ />
+ <Text
+ strong
+ className={`
+ text-xs leading-[18px] truncate
+ ${isSelected ? "text-blue-500" : "text-gray-800"}
+ `}
+ title={displayName}
+ >
+ {displayName}
+ </Text>
+ </div>
+ <Button
+ type="text"
+ size="small"
+ icon={isExpanded ? <ChevronUp size={10} /> : <Info size={10} />}
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleExpansion(tool.name);
+ }}
+ className="p-0.5 min-w-0 h-[18px] w-[18px] flex-shrink-0"
+ />
+ </div>
+
+ {/* Description */}
+ <div
+ className={`
+ flex-1 mb-1.5 overflow-hidden flex flex-col
+ ${isExpanded ? "h-auto" : "h-[26px]"}
+ `}
+ >
+ <div
+ className={`
+ text-[10px] leading-[13px] text-gray-500 overflow-hidden break-words
+ ${isExpanded ? "" : "line-clamp-2"}
+ `}
+ style={{
+ display: isExpanded ? "block" : "-webkit-box",
+ WebkitLineClamp: isExpanded ? "none" : 2,
+ WebkitBoxOrient: "vertical",
+ }}
+ >
+ {truncatedDescription}
+ </div>
+ </div>
+
+ {/* Expanded Details */}
+ {isExpanded && (
+ <div className="mb-1.5 border-t border-gray-100 pt-1.5">
+ <div className="mb-0.5">
+ <Text strong className="text-[9px]">
+ Parameters:
+ </Text>
+ </div>
+ <div className="max-h-[60px] overflow-y-auto text-[9px]">
+ {Object.keys(tool.inputSchema?.properties || {}).length === 0 ? (
+ <Text className="text-gray-400 text-[9px]">No parameters</Text>
+ ) : (
+ Object.entries(tool.inputSchema?.properties || {}).map(
+ ([key, schema]: [string, any]) => (
+ <div
+ key={key}
+ className="mb-0.5 flex items-center gap-0.5 flex-wrap"
+ >
+ <code className="text-[8px] bg-gray-100 px-0.5 py-0.5 rounded max-w-20 overflow-hidden text-ellipsis">
+ {key}
+ </code>
+ <Text className="text-gray-400 text-[8px]">
+ {schema.type || "any"}
+ </Text>
+ {tool.inputSchema?.required?.includes(key) && (
+ <div className="text-[7px] text-red-600 bg-red-50 border border-red-200 rounded px-0.5 leading-[10px]">
+ req
+ </div>
+ )}
+ </div>
+ )
+ )
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Footer with badges and param count */}
+ <div className="flex items-center justify-between mt-auto min-h-[14px]">
+ <div className="flex gap-0.5 flex-wrap items-center">
+ {badges.map((badge) => (
+ <div
+ key={badge.key}
+ className={`
+ inline-flex items-center px-0.5 py-0.5 rounded border
+ ${badge.color}
+ `}
+ title={badge.label}
+ >
+ <span className="text-[10px]">{badge.icon}</span>
+ </div>
+ ))}
+ </div>
+ <div className="flex items-center gap-0.5 flex-shrink-0">
+ <Hash size={8} className="text-gray-500" />
+ <Text className="text-[8px] text-gray-500">{paramCount}</Text>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/useMcpWebSocket.ts b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/useMcpWebSocket.ts
new file mode 100644
index 000000000..a1c56218a
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/useMcpWebSocket.ts
@@ -0,0 +1,400 @@
+import { useState, useEffect, useCallback, useRef } from "react";
+import { McpServerParams } from "../../../../../../types/datamodel";
+import {
+ ServerCapabilities,
+ Tool,
+ CallToolResult,
+} from "../../../../../mcp/api";
+import { getServerUrl } from "../../../../../../utils/utils";
+
+export interface McpWebSocketState {
+ connected: boolean;
+ connecting: boolean;
+ capabilities: ServerCapabilities | null;
+ sessionId: string | null;
+ error: string | null;
+ lastActivity: Date | null;
+}
+
+export interface McpWebSocketMessage {
+ type:
+ | "connected"
+ | "initializing"
+ | "initialized"
+ | "operation_result"
+ | "error"
+ | "pong";
+ session_id?: string;
+ capabilities?: ServerCapabilities;
+ operation?: string;
+ data?: any;
+ error?: string;
+ message?: string;
+ timestamp?: string;
+}
+
+export interface McpOperationMessage {
+ type: "operation";
+ operation: string;
+ tool_name?: string;
+ arguments?: Record<string, any>;
+ uri?: string;
+ name?: string;
+}
+
+export interface UseMcpWebSocketReturn {
+ state: McpWebSocketState;
+ connect: () => Promise<void>;
+ executeOperation: (
+ operation: Omit<McpOperationMessage, "type">
+ ) => Promise<any>;
+ ping: () => void;
+ reconnect: () => void;
+ disconnect: () => void;
+}
+
+export const useMcpWebSocket = (
+ serverParams: McpServerParams
+): UseMcpWebSocketReturn => {
+ const [state, setState] = useState<McpWebSocketState>({
+ connected: false,
+ connecting: false,
+ capabilities: null,
+ sessionId: null,
+ error: null,
+ lastActivity: null,
+ });
+
+ const wsRef = useRef<WebSocket | null>(null);
+ const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const operationPromisesRef = useRef<
+ Map<string, { resolve: (value: any) => void; reject: (error: any) => void }>
+ >(new Map());
+ const reconnectAttempts = useRef(0);
+ const maxReconnectAttempts = 5;
+ const baseReconnectDelay = 1000; // 1 second
+
+ const getWebSocketBaseUrl = useCallback((url: string): string => {
+ try {
+ let baseUrl = url.replace(/(^\w+:|^)\/\//, "");
+ if (baseUrl.startsWith("localhost")) {
+ baseUrl = baseUrl.replace("/api", "");
+ } else if (baseUrl === "/api") {
+ baseUrl = window.location.host;
+ } else {
+ baseUrl = baseUrl.replace("/api", "").replace(/\/$/, "");
+ }
+ return baseUrl;
+ } catch (error) {
+ console.error("Error processing server URL:", error);
+ throw new Error("Invalid server URL configuration");
+ }
+ }, []);
+
+ const getWebSocketUrl = useCallback(() => {
+ const serverUrl = getServerUrl();
+ const baseUrl = getWebSocketBaseUrl(serverUrl);
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ return `${protocol}//${baseUrl}`;
+ }, [getWebSocketBaseUrl]);
+
+ const cleanup = useCallback(() => {
+ if (wsRef.current) {
+ wsRef.current.close();
+ wsRef.current = null;
+ }
+ if (reconnectTimeoutRef.current) {
+ clearTimeout(reconnectTimeoutRef.current);
+ reconnectTimeoutRef.current = null;
+ }
+ // Reject all pending operations
+ operationPromisesRef.current.forEach(({ reject }) => {
+ reject(new Error("WebSocket connection closed"));
+ });
+ operationPromisesRef.current.clear();
+ }, []);
+
+ const connect = useCallback(async () => {
+ if (state.connecting || state.connected) {
+ return;
+ }
+
+ setState((prev) => ({ ...prev, connecting: true, error: null }));
+
+ try {
+ // First, get the WebSocket connection URL
+ console.log("Connecting to MCP server with params:", serverParams);
+ const serverUrl = getServerUrl();
+ const response = await fetch(`${serverUrl}/mcp/ws/connect`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ server_params: serverParams }),
+ });
+
+ console.log("Response status:", response.status, response.statusText);
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ console.error("HTTP error response:", errorText);
+ throw new Error(
+ `HTTP ${response.status}: ${
+ errorText || "Failed to create WebSocket connection"
+ }`
+ );
+ }
+
+ let connectionData;
+ try {
+ const responseText = await response.text();
+ console.log("Raw response:", responseText);
+ connectionData = JSON.parse(responseText);
+ } catch (jsonError) {
+ console.error("JSON parse error:", jsonError);
+ throw new Error(
+ `Invalid JSON response from server. Check if the MCP route is properly configured.`
+ );
+ }
+
+ if (!connectionData.status) {
+ throw new Error(
+ connectionData.message || "Failed to create WebSocket connection"
+ );
+ }
+
+ const { session_id, websocket_url } = connectionData;
+ const wsUrl = `${getWebSocketUrl()}${websocket_url}`;
+
+ // Create WebSocket connection
+ const ws = new WebSocket(wsUrl);
+ wsRef.current = ws;
+
+ ws.onopen = () => {
+ console.log(`MCP WebSocket connected to session ${session_id}`);
+ setState((prev) => ({
+ ...prev,
+ connected: true,
+ connecting: false,
+ sessionId: session_id,
+ error: null,
+ lastActivity: new Date(),
+ }));
+ reconnectAttempts.current = 0;
+ };
+
+ ws.onmessage = (event) => {
+ try {
+ const message: McpWebSocketMessage = JSON.parse(event.data);
+
+ setState((prev) => ({ ...prev, lastActivity: new Date() }));
+
+ switch (message.type) {
+ case "connected":
+ console.log("MCP session connected");
+ break;
+
+ case "initializing":
+ console.log("MCP session initializing:", message.message);
+ break;
+
+ case "initialized":
+ console.log("MCP session initialized with capabilities");
+ if (message.capabilities) {
+ // Use native MCP capabilities directly
+ console.log(
+ "Using native MCP capabilities:",
+ message.capabilities
+ );
+ setState((prev) => ({
+ ...prev,
+ capabilities: message.capabilities || null,
+ }));
+ }
+ break;
+
+ case "operation_result":
+ // Handle operation results
+ if (message.operation) {
+ const operationKey = message.operation;
+ const promise = operationPromisesRef.current.get(operationKey);
+ if (promise) {
+ promise.resolve(message.data);
+ operationPromisesRef.current.delete(operationKey);
+ }
+ }
+ break;
+
+ case "error":
+ console.error("MCP WebSocket error:", message.error);
+ setState((prev) => ({
+ ...prev,
+ error: message.error || "Unknown error",
+ }));
+
+ // If it's an operation error, reject the specific operation
+ if (message.operation) {
+ const promise = operationPromisesRef.current.get(
+ message.operation
+ );
+ if (promise) {
+ promise.reject(
+ new Error(message.error || "Operation failed")
+ );
+ operationPromisesRef.current.delete(message.operation);
+ }
+ }
+ break;
+
+ case "pong":
+ // Handle pong response
+ break;
+
+ default:
+ console.warn("Unknown MCP message type:", message.type);
+ }
+ } catch (error) {
+ console.error("Error parsing MCP WebSocket message:", error);
+ }
+ };
+
+ ws.onerror = (error) => {
+ console.error("MCP WebSocket error:", error);
+ setState((prev) => ({
+ ...prev,
+ error: "WebSocket connection error",
+ connected: false,
+ connecting: false,
+ }));
+ };
+
+ ws.onclose = (event) => {
+ console.log("MCP WebSocket closed:", event.code, event.reason);
+ setState((prev) => ({
+ ...prev,
+ connected: false,
+ connecting: false,
+ }));
+
+ // Attempt to reconnect if not manually closed
+ if (
+ event.code !== 1000 &&
+ reconnectAttempts.current < maxReconnectAttempts
+ ) {
+ const delay =
+ baseReconnectDelay * Math.pow(2, reconnectAttempts.current);
+ console.log(
+ `Attempting to reconnect in ${delay}ms (attempt ${
+ reconnectAttempts.current + 1
+ }/${maxReconnectAttempts})`
+ );
+
+ reconnectTimeoutRef.current = setTimeout(() => {
+ reconnectAttempts.current++;
+ connect();
+ }, delay);
+ }
+ };
+ } catch (error) {
+ console.error("Failed to establish MCP WebSocket connection:", error);
+ setState((prev) => ({
+ ...prev,
+ error: error instanceof Error ? error.message : "Connection failed",
+ connected: false,
+ connecting: false,
+ }));
+ }
+ }, [serverParams, state.connecting, state.connected, getWebSocketUrl]);
+
+ const executeOperation = useCallback(
+ async (operation: Omit<McpOperationMessage, "type">): Promise<any> => {
+ return new Promise((resolve, reject) => {
+ if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
+ reject(new Error("WebSocket not connected"));
+ return;
+ }
+
+ const operationKey = operation.operation;
+
+ // Store the promise for this operation
+ operationPromisesRef.current.set(operationKey, { resolve, reject });
+
+ // Send the operation message
+ const message: McpOperationMessage = {
+ type: "operation",
+ ...operation,
+ };
+
+ try {
+ wsRef.current.send(JSON.stringify(message));
+ } catch (error) {
+ operationPromisesRef.current.delete(operationKey);
+ reject(error);
+ }
+
+ // Set a timeout for the operation
+ setTimeout(() => {
+ if (operationPromisesRef.current.has(operationKey)) {
+ operationPromisesRef.current.delete(operationKey);
+ reject(new Error("Operation timeout"));
+ }
+ }, 30000); // 30 second timeout
+ });
+ },
+ []
+ );
+
+ const ping = useCallback(() => {
+ if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
+ wsRef.current.send(JSON.stringify({ type: "ping" }));
+ }
+ }, []);
+
+ const reconnect = useCallback(() => {
+ cleanup();
+ setState((prev) => ({
+ ...prev,
+ connected: false,
+ connecting: false,
+ error: null,
+ }));
+ reconnectAttempts.current = 0;
+ connect();
+ }, [cleanup, connect]);
+
+ const disconnect = useCallback(() => {
+ cleanup();
+ setState((prev) => ({
+ ...prev,
+ connected: false,
+ connecting: false,
+ sessionId: null,
+ capabilities: null,
+ error: null,
+ }));
+ }, [cleanup]);
+
+ // Manual connection only - no auto-connect
+ useEffect(() => {
+ return () => {
+ cleanup();
+ };
+ }, [cleanup]);
+
+ // Periodic ping to keep connection alive
+ useEffect(() => {
+ if (state.connected) {
+ const pingInterval = setInterval(ping, 30000); // Ping every 30 seconds
+ return () => clearInterval(pingInterval);
+ }
+ }, [state.connected, ping]);
+
+ return {
+ state,
+ connect,
+ executeOperation,
+ ping,
+ reconnect,
+ disconnect,
+ };
+};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/workbench-fields.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/workbench-fields.tsx
new file mode 100644
index 000000000..87a612d8b
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/component-editor/fields/workbench/workbench-fields.tsx
@@ -0,0 +1,956 @@
+import React, { useCallback, useState } from "react";
+import {
+ Input,
+ Select,
+ Button,
+ Space,
+ Card,
+ Collapse,
+ InputNumber,
+} from "antd";
+import {
+ PlusCircle,
+ MinusCircle,
+ Package,
+ Settings,
+ Wrench,
+ Trash2,
+ Info,
+ FileText,
+} from "lucide-react";
+import {
+ Component,
+ ComponentConfig,
+ StaticWorkbenchConfig,
+ McpWorkbenchConfig,
+ StdioServerParams,
+ SseServerParams,
+ StreamableHttpServerParams,
+ FunctionToolConfig,
+} from "../../../../../../types/datamodel";
+import {
+ isStaticWorkbench,
+ isMcpWorkbench,
+ isFunctionTool,
+} from "../../../../../../types/guards";
+import { ToolFields } from "../tool-fields";
+import { McpCapabilitiesPanel } from "./mcp-capabilities-panel";
+
+const { TextArea } = Input;
+const { Option } = Select;
+const { Panel } = Collapse;
+
+interface WorkbenchFieldsProps {
+ component: Component<ComponentConfig>;
+ onChange: (updates: Partial<Component<ComponentConfig>>) => void;
+ defaultPanelKey?: string[];
+ readonly?: boolean;
+}
+
+export const WorkbenchFields: React.FC<WorkbenchFieldsProps> = ({
+ component,
+ onChange,
+ defaultPanelKey = ["configuration", "testing"],
+ readonly = false,
+}) => {
+ const [showAddEnvVar, setShowAddEnvVar] = useState(false);
+ const [newEnvVar, setNewEnvVar] = useState({ key: "", value: "" });
+
+ const handleComponentUpdate = useCallback(
+ (updates: Partial<Component<ComponentConfig>>) => {
+ onChange({
+ ...component,
+ ...updates,
+ config: {
+ ...component.config,
+ ...(updates.config || {}),
+ },
+ });
+ },
+ [component, onChange]
+ );
+
+ // Compact overview component for readonly mode
+ const CompactOverview = () => {
+ if (isStaticWorkbench(component)) {
+ const staticConfig = component.config as StaticWorkbenchConfig;
+ return (
+ <Card className="mb-4" size="small">
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <h4 className="font-medium text-lg">
+ {component.label || "Static Workbench"}
+ </h4>
+ <span className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded">
+ Static
+ </span>
+ </div>
+ {component.description && (
+ <p className="text-sm text-secondary">{component.description}</p>
+ )}
+ <div className="flex items-center gap-4 text-sm text-gray-500">
+ <span>Version: {component.version || 1}</span>
+ <span>•</span>
+ <span>Tools: {staticConfig.tools?.length || 0}</span>
+ </div>
+ </div>
+ </Card>
+ );
+ }
+
+ if (isMcpWorkbench(component)) {
+ const mcpConfig = component.config as McpWorkbenchConfig;
+ const serverParams = mcpConfig.server_params;
+
+ let serverInfo = "";
+ if (serverParams.type === "StdioServerParams") {
+ serverInfo = `${serverParams.command || "N/A"}`;
+ } else if (serverParams.type === "SseServerParams") {
+ serverInfo = serverParams.url || "N/A";
+ } else if (serverParams.type === "StreamableHttpServerParams") {
+ serverInfo = serverParams.url || "N/A";
+ }
+
+ return (
+ <Card className="mb-4" size="small">
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <h4 className="font-medium text-lg">
+ {component.label || "MCP Workbench"}
+ </h4>
+ <span className="text-xs bg-green-100 text-green-700 px-2 py-1 rounded">
+ MCP
+ </span>
+ </div>
+ {component.description && (
+ <p className="text-sm text-secondary">{component.description}</p>
+ )}
+ <div className="flex items-center gap-4 text-sm text-secondary">
+ <span>Version: {component.version || 1}</span>
+ <span>•</span>
+ <span>Type: {serverParams.type.replace("ServerParams", "")}</span>
+ <span>•</span>
+ <span className="truncate max-w-40">{serverInfo}</span>
+ </div>
+ </div>
+ </Card>
+ );
+ }
+
+ return null;
+ };
+
+ if (isStaticWorkbench(component)) {
+ const staticConfig = component.config as StaticWorkbenchConfig;
+
+ const handleAddTool = () => {
+ const newTool: Component<FunctionToolConfig> = {
+ provider: "autogen_core.tools.FunctionTool",
+ component_type: "tool",
+ version: 1,
+ component_version: 1,
+ label: "New Tool",
+ description: "A new tool",
+ config: {
+ source_code:
+ 'def new_tool():\n """A new tool function"""\n return "Hello from new tool"',
+ name: "new_tool",
+ description: "A new tool",
+ global_imports: [],
+ has_cancellation_support: false,
+ },
+ };
+
+ const updatedTools = [...(staticConfig.tools || []), newTool];
+ handleComponentUpdate({
+ config: {
+ ...staticConfig,
+ tools: updatedTools,
+ },
+ });
+ };
+
+ const handleUpdateTool = (
+ index: number,
+ updatedTool: Partial<Component<ComponentConfig>>
+ ) => {
+ const updatedTools = [...(staticConfig.tools || [])];
+ updatedTools[index] = {
+ ...updatedTools[index],
+ ...updatedTool,
+ } as Component<any>;
+ handleComponentUpdate({
+ config: {
+ ...staticConfig,
+ tools: updatedTools,
+ },
+ });
+ };
+
+ const handleDeleteTool = (index: number) => {
+ const updatedTools = [...(staticConfig.tools || [])];
+ updatedTools.splice(index, 1);
+ handleComponentUpdate({
+ config: {
+ ...staticConfig,
+ tools: updatedTools,
+ },
+ });
+ };
+
+ // Helper function to create dynamic accordion title
+ const getComponentDetailsTitle = () => {
+ const label = component.label || "";
+ const displayName =
+ label.length > 20 ? `${label.substring(0, 30)}...` : label;
+ return (
+ <div className="flex items-center gap-2">
+ <Info className="w-4 h-4 text-blue-500" />
+ <span className="font-medium">
+ Component
+ {displayName && (
+ <span className="text-gray-500 font-normal ml-2">
+ ({displayName})
+ </span>
+ )}
+ </span>
+ </div>
+ );
+ };
+
+ return (
+ <div className="space-y-4">
+ {readonly ? (
+ <>
+ <CompactOverview />
+ <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
+ <p className="text-sm text-yellow-800">
+ <strong>Note:</strong> Static workbenches don't have runtime
+ testing capabilities. Tools are predefined and tested through
+ the component's execution environment.
+ </p>
+ </div>
+ </>
+ ) : (
+ <Collapse
+ defaultActiveKey={defaultPanelKey}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "details",
+ label: getComponentDetailsTitle(),
+ children: (
+ <div className="space-y-4">
+ <label className="block">
+ <span className="text-sm font-medium text-secondary">
+ Label
+ </span>
+ <Input
+ value={component.label || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ label: e.target.value })
+ }
+ placeholder="Workbench label"
+ className="mt-1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-secondary">
+ Description
+ </span>
+ <TextArea
+ value={component.description || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ description: e.target.value })
+ }
+ placeholder="Workbench description"
+ rows={3}
+ className="mt-1"
+ />
+ </label>
+
+ <div className="grid grid-cols-2 gap-4">
+ <label className="block">
+ <span className="text-sm font-medium text-secondary">
+ Version
+ </span>
+ <InputNumber
+ value={component.version || 1}
+ onChange={(value) =>
+ handleComponentUpdate({ version: value || 1 })
+ }
+ min={1}
+ precision={0}
+ className="w-full mt-1"
+ placeholder="e.g., 1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-secondary">
+ Component Version
+ </span>
+ <InputNumber
+ value={component.component_version || 1}
+ onChange={(value) =>
+ handleComponentUpdate({
+ component_version: value || 1,
+ })
+ }
+ min={1}
+ precision={0}
+ className="w-full mt-1"
+ placeholder="e.g., 1"
+ />
+ </label>
+ </div>
+ </div>
+ ),
+ },
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-green-500" />
+ <span className="font-medium">
+ Static Workbench Configuration
+ </span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-sm text-secondary">
+ <Package className="w-4 h-4" />
+ <span>
+ Tools: {staticConfig.tools?.length || 0} configured
+ </span>
+ </div>
+ <Button
+ type="primary"
+ size="small"
+ onClick={handleAddTool}
+ icon={<PlusCircle className="h-4 w-4" />}
+ >
+ Add Tool
+ </Button>
+ </div>
+
+ {staticConfig.tools && staticConfig.tools.length > 0 ? (
+ <Collapse className="">
+ {staticConfig.tools.map((tool, index) => {
+ if (!isFunctionTool(tool)) return null;
+
+ return (
+ <Panel
+ key={index}
+ header={
+ <div className="flex items-center justify-between w-full">
+ <div className="flex items-center gap-2">
+ <Wrench className="w-4 h-4 text-blue-500" />
+ <span className="font-medium">
+ {tool.config?.name ||
+ tool.label ||
+ "Unnamed Tool"}
+ </span>
+ <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded">
+ {tool.provider}
+ </span>
+ </div>
+ {staticConfig.tools!.length > 1 && (
+ <Button
+ type="text"
+ size="small"
+ danger
+ onClick={(e) => {
+ e.stopPropagation(); // Prevent accordion toggle
+ handleDeleteTool(index);
+ }}
+ icon={<Trash2 className="h-4 w-4" />}
+ />
+ )}
+ </div>
+ }
+ >
+ <ToolFields
+ component={tool}
+ onChange={(updates) =>
+ handleUpdateTool(index, updates)
+ }
+ />
+ </Panel>
+ );
+ })}
+ </Collapse>
+ ) : (
+ <div className="text-center text-gray-500 py-8 border-2 border-dashed border-gray-200 rounded-lg">
+ <Package className="w-12 h-12 mx-auto mb-4 text-gray-400" />
+ <p className="mb-4">No tools configured</p>
+ <Button type="dashed" onClick={handleAddTool}>
+ Add Your First Tool
+ </Button>
+ </div>
+ )}
+
+ <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
+ <p className="text-sm text-blue-800">
+ Static workbenches contain a predefined set of tools.
+ Click on a tool above to edit its configuration, or add
+ new tools using the "Add Tool" button.
+ </p>
+ </div>
+ </div>
+ ),
+ },
+ ]}
+ />
+ )}
+ </div>
+ );
+ }
+
+ if (isMcpWorkbench(component)) {
+ const mcpConfig = component.config as McpWorkbenchConfig;
+ const serverParams = mcpConfig.server_params;
+
+ const handleServerParamsUpdate = (
+ updates: Partial<typeof serverParams>
+ ) => {
+ handleComponentUpdate({
+ config: {
+ ...component.config,
+ server_params: {
+ ...serverParams,
+ ...updates,
+ },
+ },
+ });
+ };
+
+ const handleAddEnvVar = () => {
+ if (!newEnvVar.key || !newEnvVar.value) return;
+
+ const currentEnv =
+ (serverParams.type === "StdioServerParams" && serverParams.env) || {};
+ const updatedEnv = {
+ ...currentEnv,
+ [newEnvVar.key]: newEnvVar.value,
+ };
+
+ if (serverParams.type === "StdioServerParams") {
+ handleServerParamsUpdate({ env: updatedEnv });
+ }
+
+ setNewEnvVar({ key: "", value: "" });
+ setShowAddEnvVar(false);
+ };
+
+ const handleRemoveEnvVar = (key: string) => {
+ if (serverParams.type === "StdioServerParams" && serverParams.env) {
+ const updatedEnv = { ...serverParams.env };
+ delete updatedEnv[key];
+ handleServerParamsUpdate({ env: updatedEnv });
+ }
+ };
+
+ // Helper function to create dynamic accordion title
+ const getComponentDetailsTitle = () => {
+ const label = component.label || "";
+ const displayName =
+ label.length > 30 ? `${label.substring(0, 30)}...` : label;
+ return (
+ <div className="flex items-center gap-2">
+ <Info className="w-4 h-4 text-blue-500" />
+ <span className="font-medium">
+ Details
+ {displayName && (
+ <span className="text-gray-500 font-normal ml-2">
+ ({displayName})
+ </span>
+ )}
+ </span>
+ </div>
+ );
+ };
+
+ return (
+ <div className="space-y-4 scroll h-full">
+ {readonly ? (
+ <div className=" h-full">
+ <CompactOverview />
+ <Collapse
+ defaultActiveKey={["testing"]}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "testing",
+ label: (
+ <div className="flex items-center gap-2">
+ <FileText className="w-4 h-4 text-purple-500" />
+ <span className="font-medium">MCP Testing Panel</span>
+ </div>
+ ),
+ children: (
+ <>
+ <McpCapabilitiesPanel serverParams={serverParams} />
+ </>
+ ),
+ },
+ ]}
+ />
+ </div>
+ ) : (
+ <Collapse
+ defaultActiveKey={defaultPanelKey}
+ className="border-0"
+ expandIconPosition="end"
+ items={[
+ {
+ key: "details",
+ label: getComponentDetailsTitle(),
+ children: (
+ <div className="space-y-4">
+ <label className="block">
+ <span className="text-sm font-medium text-secondary">
+ Label
+ </span>
+ <Input
+ value={component.label || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ label: e.target.value })
+ }
+ placeholder="Workbench label"
+ className="mt-1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-secondary">
+ Description
+ </span>
+ <TextArea
+ value={component.description || ""}
+ onChange={(e) =>
+ handleComponentUpdate({ description: e.target.value })
+ }
+ placeholder="Workbench description"
+ rows={3}
+ className="mt-1"
+ />
+ </label>
+
+ <div className="grid grid-cols-2 gap-4">
+ <label className="block">
+ <span className="text-sm font-medium text-secondary">
+ Version
+ </span>
+ <InputNumber
+ value={component.version || 1}
+ onChange={(value) =>
+ handleComponentUpdate({ version: value || 1 })
+ }
+ min={1}
+ precision={0}
+ className="w-full mt-1"
+ placeholder="e.g., 1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-secondary">
+ Component Version
+ </span>
+ <InputNumber
+ value={component.component_version || 1}
+ onChange={(value) =>
+ handleComponentUpdate({
+ component_version: value || 1,
+ })
+ }
+ min={1}
+ precision={0}
+ className="w-full mt-1"
+ placeholder="e.g., 1"
+ />
+ </label>
+ </div>
+ </div>
+ ),
+ },
+ {
+ key: "configuration",
+ label: (
+ <div className="flex items-center gap-2">
+ <Settings className="w-4 h-4 text-green-500" />
+ <span className="font-medium">Configuration</span>
+ </div>
+ ),
+ children: (
+ <div className="space-y-4">
+ <div className="flex items-center gap-2 text-sm text-secondary">
+ <Settings className="w-4 h-4" />
+ <span>Server Type: {serverParams.type}</span>
+ </div>
+
+ {serverParams.type === "StdioServerParams" && (
+ <>
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Command
+ </span>
+ <Input
+ value={serverParams.command || ""}
+ onChange={(e) =>
+ handleServerParamsUpdate({
+ command: e.target.value,
+ })
+ }
+ placeholder="e.g., uvx"
+ className="mt-1"
+ />
+ </label>
+
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-primary">
+ Arguments
+ </span>
+ <Button
+ type="dashed"
+ size="small"
+ icon={<PlusCircle className="w-4 h-4" />}
+ onClick={() => {
+ const currentArgs = serverParams.args || [];
+ handleServerParamsUpdate({
+ args: [...currentArgs, ""],
+ });
+ }}
+ >
+ Add Argument
+ </Button>
+ </div>
+
+ <div className="space-y-2">
+ {(serverParams.args || []).length === 0 ? (
+ <div className="text-sm text-secondary italic p-3 border border-dashed border-secondary rounded">
+ No arguments. Click "Add Argument" to add
+ command line arguments.
+ </div>
+ ) : (
+ (serverParams.args || []).map((arg, index) => (
+ <div
+ key={index}
+ className="flex items-center gap-2"
+ >
+ <span className="text-xs text-secondary w-8">
+ {index}
+ </span>
+ <Input
+ value={arg}
+ onChange={(e) => {
+ const newArgs = [
+ ...(serverParams.args || []),
+ ];
+ newArgs[index] = e.target.value;
+ handleServerParamsUpdate({
+ args: newArgs,
+ });
+ }}
+ placeholder={`Argument ${index}`}
+ className="flex-1"
+ />
+ <Button
+ type="text"
+ size="small"
+ icon={<Trash2 className="w-4 h-4" />}
+ onClick={() => {
+ const newArgs = [
+ ...(serverParams.args || []),
+ ];
+ newArgs.splice(index, 1);
+ handleServerParamsUpdate({
+ args: newArgs,
+ });
+ }}
+ className="text-red-500 hover:text-red-700"
+ />
+ </div>
+ ))
+ )}
+ </div>
+
+ {(serverParams.args || []).length > 0 && (
+ <div className="text-xs text-secondary bg-secondary/30 p-2 rounded">
+ <strong>Command preview:</strong>{" "}
+ {serverParams.command}{" "}
+ {(serverParams.args || []).join(" ")}
+ </div>
+ )}
+ </div>
+
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Read Timeout (seconds)
+ </span>
+ <Input
+ type="number"
+ value={serverParams.read_timeout_seconds || 5}
+ onChange={(e) =>
+ handleServerParamsUpdate({
+ read_timeout_seconds:
+ parseFloat(e.target.value) || 5,
+ })
+ }
+ className="mt-1"
+ />
+ </label>
+
+ <div className="space-y-2">
+ <span className="text-sm font-medium text-primary">
+ Environment Variables
+ </span>
+
+ {serverParams.env &&
+ Object.keys(serverParams.env).length > 0 && (
+ <div className="space-y-2">
+ {Object.entries(serverParams.env).map(
+ ([key, value]) => (
+ <div
+ key={key}
+ className="flex items-center gap-2 bg-gray-50 rounded px-3 py-2"
+ >
+ <span className="font-mono text-sm flex-1">
+ {key}={value}
+ </span>
+ <Button
+ type="text"
+ size="small"
+ onClick={() => handleRemoveEnvVar(key)}
+ icon={
+ <MinusCircle className="h-4 w-4" />
+ }
+ />
+ </div>
+ )
+ )}
+ </div>
+ )}
+
+ {showAddEnvVar ? (
+ <div className="border rounded p-3 space-y-3">
+ <Space>
+ <Input
+ placeholder="Variable name"
+ value={newEnvVar.key}
+ onChange={(e) =>
+ setNewEnvVar((prev) => ({
+ ...prev,
+ key: e.target.value,
+ }))
+ }
+ />
+ <Input
+ placeholder="Variable value"
+ value={newEnvVar.value}
+ onChange={(e) =>
+ setNewEnvVar((prev) => ({
+ ...prev,
+ value: e.target.value,
+ }))
+ }
+ onKeyDown={(e) => {
+ if (
+ e.key === "Enter" &&
+ newEnvVar.key &&
+ newEnvVar.value
+ ) {
+ handleAddEnvVar();
+ }
+ }}
+ />
+ <Button
+ onClick={handleAddEnvVar}
+ disabled={!newEnvVar.key || !newEnvVar.value}
+ >
+ Add
+ </Button>
+ </Space>
+ </div>
+ ) : (
+ <Button
+ type="dashed"
+ onClick={() => setShowAddEnvVar(true)}
+ className="w-full"
+ >
+ <PlusCircle className="h-4 w-4 mr-2" />
+ Add Environment Variable
+ </Button>
+ )}
+ </div>
+ </>
+ )}
+
+ {serverParams.type === "SseServerParams" && (
+ <>
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Server URL
+ </span>
+ <Input
+ value={serverParams.url || ""}
+ onChange={(e) =>
+ handleServerParamsUpdate({ url: e.target.value })
+ }
+ placeholder="https://your-mcp-server.com"
+ className="mt-1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Timeout (seconds)
+ </span>
+ <Input
+ type="number"
+ value={serverParams.timeout || 5}
+ onChange={(e) =>
+ handleServerParamsUpdate({
+ timeout: parseFloat(e.target.value) || 5,
+ })
+ }
+ className="mt-1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ SSE Read Timeout (seconds)
+ </span>
+ <Input
+ type="number"
+ value={serverParams.sse_read_timeout || 300}
+ onChange={(e) =>
+ handleServerParamsUpdate({
+ sse_read_timeout:
+ parseFloat(e.target.value) || 300,
+ })
+ }
+ className="mt-1"
+ />
+ </label>
+ </>
+ )}
+
+ {serverParams.type === "StreamableHttpServerParams" && (
+ <>
+ <label className="block">
+ <span className="text-sm font-medium text-secondary">
+ Server URL
+ </span>
+ <Input
+ type="url"
+ value={serverParams.url || ""}
+ onChange={(e) =>
+ handleServerParamsUpdate({ url: e.target.value })
+ }
+ placeholder="https://your-streamable-http-server.com"
+ className="mt-1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ Timeout (seconds)
+ </span>
+ <Input
+ type="number"
+ value={serverParams.timeout || 30}
+ onChange={(e) =>
+ handleServerParamsUpdate({
+ timeout: parseFloat(e.target.value) || 30,
+ })
+ }
+ className="mt-1"
+ />
+ </label>
+
+ <label className="block">
+ <span className="text-sm font-medium text-primary">
+ SSE Read Timeout (seconds)
+ </span>
+ <Input
+ type="number"
+ value={serverParams.sse_read_timeout || 300}
+ onChange={(e) =>
+ handleServerParamsUpdate({
+ sse_read_timeout:
+ parseFloat(e.target.value) || 300,
+ })
+ }
+ className="mt-1"
+ />
+ </label>
+
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={serverParams.terminate_on_close ?? true}
+ onChange={(e) =>
+ handleServerParamsUpdate({
+ terminate_on_close: e.target.checked,
+ })
+ }
+ className="rounded"
+ />
+ <span className="text-sm font-medium text-primary">
+ Terminate on Close
+ </span>
+ </label>
+ </>
+ )}
+
+ <div className="bg-secondary/30 border border-secondary rounded-lg p-4">
+ <p className="text-sm text-secondary">
+ {serverParams.type === "StreamableHttpServerParams"
+ ? "Streamable HTTP workbenches connect to MCP servers over HTTP with streaming capabilities, ideal for cloud-based services and web APIs."
+ : "MCP (Model Context Protocol) workbenches connect to external tool servers that provide dynamic tool capabilities. The tools available depend on what the MCP server provides at runtime."}
+ </p>
+ </div>
+ </div>
+ ),
+ },
+ {
+ key: "testing",
+ label: (
+ <div className="flex items-center gap-2">
+ <FileText className="w-4 h-4 text-purple-500" />
+ <span className="font-medium">MCP Testing Panel</span>
+ </div>
+ ),
+ children: (
+ <>
+ <McpCapabilitiesPanel serverParams={serverParams} />
+ </>
+ ),
+ },
+ ]}
+ />
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="text-center text-gray-500 py-8">
+ <Package className="w-12 h-12 mx-auto mb-4 text-gray-400" />
+ <p>Unknown workbench type</p>
+ </div>
+ </div>
+ );
+};
+
+export default React.memo(WorkbenchFields);
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/layout-storage.ts b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/layout-storage.ts
new file mode 100644
index 000000000..f3085ee53
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/layout-storage.ts
@@ -0,0 +1,197 @@
+import { Component, ComponentConfig } from "../../../types/datamodel";
+import { CustomNode } from "./types";
+
+interface Position {
+ x: number;
+ y: number;
+}
+
+interface StoredNodePosition {
+ position: Position;
+ isUserPositioned: boolean;
+ timestamp: number;
+}
+
+interface LayoutStorage {
+ [teamId: string]: {
+ [componentKey: string]: StoredNodePosition;
+ };
+}
+
+const LAYOUT_STORAGE_KEY = "teambuilder_layout";
+const STORAGE_VERSION = 1;
+const MAX_STORAGE_AGE = 30 * 24 * 60 * 60 * 1000; // 30 days in milliseconds
+
+// Simple hash function for component config
+const hashConfig = (config: any): string => {
+ const str = JSON.stringify(config);
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ const char = str.charCodeAt(i);
+ hash = (hash << 5) - hash + char;
+ hash = hash & hash; // Convert to 32-bit integer
+ }
+ return hash.toString(36);
+};
+
+// Generate stable key for a component
+export const generateComponentKey = (
+ component: Component<ComponentConfig>
+): string => {
+ const configHash = hashConfig(component.config);
+ const label = component.label || component.component_type;
+ return `${component.component_type}_${label}_${configHash}`;
+};
+
+// Get layout storage from localStorage
+const getLayoutStorage = (): LayoutStorage => {
+ try {
+ const stored = localStorage.getItem(LAYOUT_STORAGE_KEY);
+ if (!stored) return {};
+
+ const parsed = JSON.parse(stored);
+ if (parsed.version !== STORAGE_VERSION) {
+ // Version mismatch, clear storage
+ localStorage.removeItem(LAYOUT_STORAGE_KEY);
+ return {};
+ }
+
+ return parsed.data || {};
+ } catch (error) {
+ console.warn("Failed to parse layout storage:", error);
+ localStorage.removeItem(LAYOUT_STORAGE_KEY);
+ return {};
+ }
+};
+
+// Save layout storage to localStorage
+const saveLayoutStorage = (storage: LayoutStorage): void => {
+ try {
+ const toStore = {
+ version: STORAGE_VERSION,
+ data: storage,
+ };
+ localStorage.setItem(LAYOUT_STORAGE_KEY, JSON.stringify(toStore));
+ } catch (error) {
+ console.warn("Failed to save layout storage:", error);
+ }
+};
+
+// Clean up old entries
+const cleanupOldEntries = (storage: LayoutStorage): LayoutStorage => {
+ const now = Date.now();
+ const cleaned: LayoutStorage = {};
+
+ for (const [teamId, teamLayout] of Object.entries(storage)) {
+ const cleanedTeamLayout: { [key: string]: StoredNodePosition } = {};
+
+ for (const [componentKey, position] of Object.entries(teamLayout)) {
+ if (now - position.timestamp < MAX_STORAGE_AGE) {
+ cleanedTeamLayout[componentKey] = position;
+ }
+ }
+
+ if (Object.keys(cleanedTeamLayout).length > 0) {
+ cleaned[teamId] = cleanedTeamLayout;
+ }
+ }
+
+ return cleaned;
+};
+
+// Save node position to storage
+export const saveNodePosition = (
+ teamId: string,
+ component: Component<ComponentConfig>,
+ position: Position,
+ isUserPositioned: boolean = true
+): void => {
+ const componentKey = generateComponentKey(component);
+ let storage = getLayoutStorage();
+
+ // Clean up old entries periodically
+ storage = cleanupOldEntries(storage);
+
+ if (!storage[teamId]) {
+ storage[teamId] = {};
+ }
+
+ storage[teamId][componentKey] = {
+ position,
+ isUserPositioned,
+ timestamp: Date.now(),
+ };
+
+ saveLayoutStorage(storage);
+};
+
+// Get stored position for a component
+export const getStoredPosition = (
+ teamId: string,
+ component: Component<ComponentConfig>
+): StoredNodePosition | null => {
+ const componentKey = generateComponentKey(component);
+ const storage = getLayoutStorage();
+
+ return storage[teamId]?.[componentKey] || null;
+};
+
+// Check if a component has a user-positioned stored position
+export const isComponentUserPositioned = (
+ teamId: string,
+ component: Component<ComponentConfig>
+): boolean => {
+ const stored = getStoredPosition(teamId, component);
+ return stored?.isUserPositioned || false;
+};
+
+// Clear all layout storage for a specific team
+export const clearTeamLayoutStorage = (teamId: string): void => {
+ const storage = getLayoutStorage();
+ delete storage[teamId];
+ saveLayoutStorage(storage);
+};
+
+// Clear all layout storage (for logout, etc.)
+export const clearAllLayoutStorage = (): void => {
+ localStorage.removeItem(LAYOUT_STORAGE_KEY);
+};
+
+// Mark a node as user-positioned in storage
+export const markNodeAsUserPositioned = (
+ teamId: string,
+ node: CustomNode,
+ position: Position
+): void => {
+ saveNodePosition(teamId, node.data.component, position, true);
+};
+
+// Clear user-positioned flag for a team (for auto-layout)
+export const clearUserPositionedFlags = (teamId: string): void => {
+ const storage = getLayoutStorage();
+ const teamLayout = storage[teamId];
+
+ if (teamLayout) {
+ for (const componentKey in teamLayout) {
+ teamLayout[componentKey].isUserPositioned = false;
+ }
+ saveLayoutStorage(storage);
+ }
+};
+
+// Get all user-positioned component keys for a team
+export const getUserPositionedComponentKeys = (teamId: string): Set<string> => {
+ const storage = getLayoutStorage();
+ const teamLayout = storage[teamId];
+ const userPositioned = new Set<string>();
+
+ if (teamLayout) {
+ for (const [componentKey, position] of Object.entries(teamLayout)) {
+ if (position.isUserPositioned) {
+ userPositioned.add(componentKey);
+ }
+ }
+ }
+
+ return userPositioned;
+};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/library.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/library.tsx
index 2fad82600..eab873cdf 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/library.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/library.tsx
@@ -11,6 +11,7 @@ import {
Maximize2,
Minimize2,
GripVertical,
+ Package,
} from "lucide-react";
import Sider from "antd/es/layout/Sider";
import { ComponentTypes, Gallery } from "../../../types/datamodel";
@@ -100,7 +101,16 @@ export const ComponentLibrary: React.FC<LibraryProps> = ({
icon: <Brain className="w-4 h-4" />,
},
{
- title: "Tools",
+ title: "Workbenches",
+ type: "workbench" as ComponentTypes,
+ items: defaultGallery.config.components.workbenches?.map((workbench) => ({
+ label: workbench.label || workbench.provider.split('.').pop(),
+ config: workbench,
+ })) || [],
+ icon: <Package className="w-4 h-4" />,
+ },
+ {
+ title: "Tools (Deprecated)",
type: "tool" as ComponentTypes,
items: defaultGallery.config.components.tools.map((tool) => ({
label: tool.config?.name || tool.label,
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/nodes.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/nodes.tsx
index ada2bbec3..f0538a994 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/nodes.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/nodes.tsx
@@ -16,11 +16,15 @@ import {
Trash2Icon,
Edit,
Bot,
+ Package,
} from "lucide-react";
import { CustomNode } from "./types";
import {
AgentConfig,
TeamConfig,
+ WorkbenchConfig,
+ StaticWorkbenchConfig,
+ McpWorkbenchConfig,
ComponentTypes,
Component,
ComponentConfig,
@@ -31,7 +35,10 @@ import { useTeamBuilderStore } from "./store";
import {
isAssistantAgent,
isSelectorTeam,
+ isSwarmTeam,
isWebSurferAgent,
+ isAnyStaticWorkbench,
+ isMcpWorkbench,
} from "../../../types/guards";
// Icon mapping for different node types
@@ -44,6 +51,7 @@ export const iconMap: Record<
tool: Wrench,
model: Brain,
termination: Timer,
+ workbench: Package,
};
interface DroppableZoneProps {
@@ -203,13 +211,23 @@ export const TeamNode = memo<NodeProps<CustomNode>>((props) => {
const hasModel = isSelectorTeam(component) && !!component.config.model_client;
const participantCount = component.config.participants?.length || 0;
+ // Get team type label
+ const teamType = isSwarmTeam(component)
+ ? "Swarm"
+ : isSelectorTeam(component)
+ ? "Selector"
+ : "RoundRobin";
+
return (
<BaseNode
{...props}
icon={iconMap.team}
headerContent={
<div className="flex gap-2 mt-2">
- <ConnectionBadge connected={hasModel} label="Model" />
+ <ConnectionBadge connected={true} label={teamType} />
+ {isSelectorTeam(component) && (
+ <ConnectionBadge connected={hasModel} label="Model" />
+ )}
<ConnectionBadge
connected={participantCount > 0}
label={`${participantCount} Agent${
@@ -237,6 +255,11 @@ export const TeamNode = memo<NodeProps<CustomNode>>((props) => {
/>
</div>
)}
+ {isSwarmTeam(component) && (
+ <div className="mt-1 text-xs text-gray-600">
+ Handoff-based agent coordination
+ </div>
+ )}
</div>
}
>
@@ -335,9 +358,65 @@ export const AgentNode = memo<NodeProps<CustomNode>>((props) => {
const component = props.data.component as Component<AgentConfig>;
const hasModel =
isAssistantAgent(component) && !!component.config.model_client;
- const toolCount = isAssistantAgent(component)
- ? component.config.tools?.length || 0
- : 0;
+
+ // Get workbench info instead of direct tools
+ const workbenchInfos = (() => {
+ if (!isAssistantAgent(component)) return [];
+
+ const workbenchConfig = component.config.workbench;
+ if (!workbenchConfig) return [];
+
+ // Handle both single workbench object and array of workbenches
+ const workbenches = Array.isArray(workbenchConfig)
+ ? workbenchConfig
+ : [workbenchConfig];
+
+ return workbenches.map((workbench) => {
+ if (!workbench) {
+ return {
+ hasWorkbench: false,
+ toolCount: 0,
+ workbenchType: "unknown" as const,
+ serverType: null,
+ workbench,
+ };
+ }
+
+ if (isAnyStaticWorkbench(workbench)) {
+ return {
+ hasWorkbench: true,
+ toolCount:
+ (workbench as Component<StaticWorkbenchConfig>).config.tools
+ ?.length || 0,
+ workbenchType: "static" as const,
+ serverType: null,
+ workbench,
+ };
+ } else if (isMcpWorkbench(workbench)) {
+ const serverType = workbench.config.server_params?.type || "unknown";
+ return {
+ hasWorkbench: true,
+ toolCount: 0,
+ workbenchType: "mcp" as const,
+ serverType: serverType,
+ workbench,
+ };
+ }
+
+ return {
+ hasWorkbench: true,
+ toolCount: 0,
+ workbenchType: "unknown" as const,
+ serverType: null,
+ workbench,
+ };
+ });
+ })();
+
+ const totalToolCount = workbenchInfos.reduce(
+ (sum, info) => sum + (info.workbenchType === "static" ? info.toolCount : 0),
+ 0
+ );
return (
<BaseNode
@@ -349,8 +428,10 @@ export const AgentNode = memo<NodeProps<CustomNode>>((props) => {
<>
<ConnectionBadge connected={hasModel} label="Model" />
<ConnectionBadge
- connected={toolCount > 0}
- label={`${toolCount} Tools`}
+ connected={workbenchInfos.length > 0}
+ label={`${workbenchInfos.length} Workbench${
+ workbenchInfos.length !== 1 ? "es" : ""
+ } (${totalToolCount} Tool${totalToolCount !== 1 ? "s" : ""})`}
/>
</>
)}
@@ -376,13 +457,6 @@ export const AgentNode = memo<NodeProps<CustomNode>>((props) => {
{(isAssistantAgent(component) || isWebSurferAgent(component)) && (
<>
<NodeSection title="Model">
- {/* <Handle
- type="target"
- position={Position.Left}
- id={`${props.id}-model-input-handle`}
- className="my-left-handle"
- /> */}
-
<div className="relative">
{component.config?.model_client && (
<div className="text-sm">
@@ -401,33 +475,67 @@ export const AgentNode = memo<NodeProps<CustomNode>>((props) => {
</NodeSection>
{isAssistantAgent(component) && (
- <NodeSection title="Tools">
- {/* <Handle
- type="target"
- position={Position.Left}
- id={`${props.id}-tool-input-handle`}
- className="my-left-handle"
- /> */}
- <div className="space-y-1">
- {component.config.tools && toolCount > 0 && (
- <div className="space-y-1">
- {component.config.tools.map((tool, index) => (
- <div
- key={index}
- className="relative text-sm py-1 px-2 bg-white rounded flex items-center gap-2"
- >
- <Wrench className="w-4 h-4 text-gray-500" />
- <span>{tool.config.name}</span>
+ <NodeSection title={`Workbenches (${workbenchInfos.length})`}>
+ <Handle
+ type="target"
+ position={Position.Left}
+ id={`${props.id}-workbench-input-handle`}
+ className="my-left-handle"
+ />
+ <div className="space-y-3">
+ {workbenchInfos.length > 0 ? (
+ workbenchInfos.map((workbenchInfo, index) => (
+ <div key={index} className="space-y-1">
+ <div className="text-sm py-1 px-2 bg-white rounded flex items-center gap-2">
+ <Package className="w-4 h-4 text-gray-500" />
+ <span>
+ {workbenchInfo.workbenchType === "static"
+ ? `Static Workbench (${
+ workbenchInfo.toolCount
+ } Tool${
+ workbenchInfo.toolCount !== 1 ? "s" : ""
+ })`
+ : workbenchInfo.workbenchType === "mcp"
+ ? `MCP Workbench (${workbenchInfo.serverType})`
+ : `Workbench (${
+ (workbenchInfo.workbench as any)?.provider ||
+ "Unknown"
+ })`}
+ </span>
</div>
- ))}
+ {workbenchInfo.workbenchType === "static" &&
+ workbenchInfo.toolCount > 0 && (
+ <div className="ml-2">
+ {(
+ workbenchInfo.workbench as Component<StaticWorkbenchConfig>
+ ).config.tools.map((tool, toolIndex) => (
+ <div
+ key={toolIndex}
+ className="text-sm py-1 px-2 bg-white rounded flex items-center gap-2 mb-1"
+ >
+ <Wrench className="w-4 h-4 text-gray-500" />
+ <span className="truncate text-xs">
+ {tool.config.name ||
+ tool.label ||
+ "Unnamed Tool"}
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ ))
+ ) : (
+ <div className="text-xs text-gray-500 text-center p-2">
+ No workbenches connected
</div>
)}
<DroppableZone
- id={`${props.id}@@@tool-zone`}
- accepts={["tool"]}
+ id={`${props.id}@@@workbench-zone`}
+ accepts={["workbench"]}
>
<div className="text-secondary text-xs my-1 text-center">
- Drop tools here
+ Drop workbench here
</div>
</DroppableZone>
</div>
@@ -441,15 +549,133 @@ export const AgentNode = memo<NodeProps<CustomNode>>((props) => {
AgentNode.displayName = "AgentNode";
+// Workbench Node
+export const WorkbenchNode = memo<NodeProps<CustomNode>>((props) => {
+ const component = props.data.component as Component<WorkbenchConfig>;
+
+ const workbenchInfo = (() => {
+ if (isAnyStaticWorkbench(component)) {
+ const toolCount =
+ (component as Component<StaticWorkbenchConfig>).config.tools?.length ||
+ 0;
+ return {
+ type: "static" as const,
+ toolCount,
+ subtitle: `${toolCount} static tool${toolCount !== 1 ? "s" : ""}`,
+ hasContent: toolCount > 0,
+ };
+ } else if (isMcpWorkbench(component)) {
+ const serverType = component.config.server_params?.type || "unknown";
+ return {
+ type: "mcp" as const,
+ toolCount: 0, // Dynamic - unknown count
+ subtitle: `MCP Server (${serverType})`,
+ hasContent: true,
+ };
+ }
+ return {
+ type: "unknown" as const,
+ toolCount: 0,
+ subtitle: "Unknown workbench type",
+ hasContent: false,
+ };
+ })();
+
+ return (
+ <BaseNode
+ {...props}
+ icon={iconMap.workbench}
+ headerContent={
+ <div className="flex gap-2 mt-2">
+ <ConnectionBadge
+ connected={workbenchInfo.hasContent}
+ label={workbenchInfo.subtitle}
+ />
+ </div>
+ }
+ descriptionContent={
+ <div>
+ <div className="break-words truncate mb-1">
+ {component.description || "Workbench for managing tools"}
+ </div>
+ </div>
+ }
+ >
+ <Handle
+ type="source"
+ position={Position.Right}
+ id={`${props.id}-workbench-output-handle`}
+ className="my-right-handle"
+ />
+
+ {/* Static Workbench Content */}
+ {workbenchInfo.type === "static" && (
+ <NodeSection title={`Tools (${workbenchInfo.toolCount})`}>
+ <div className="space-y-1">
+ {workbenchInfo.toolCount > 0 ? (
+ (component as Component<StaticWorkbenchConfig>).config.tools.map(
+ (tool, index) => (
+ <div
+ key={index}
+ className="text-sm py-1 px-2 bg-white rounded flex items-center gap-2"
+ >
+ <Wrench className="w-4 h-4 text-gray-500" />
+ <span className="truncate text-xs">
+ {tool.config.name || tool.label || "Unnamed Tool"}
+ </span>
+ </div>
+ )
+ )
+ ) : (
+ <div className="text-xs text-gray-500 text-center p-2">
+ No tools configured
+ </div>
+ )}
+ <DroppableZone id={`${props.id}@@@tool-zone`} accepts={["tool"]}>
+ <div className="text-secondary text-xs my-1 text-center">
+ Drop tool here
+ </div>
+ </DroppableZone>
+ </div>
+ </NodeSection>
+ )}
+
+ {/* MCP Workbench Content */}
+ {workbenchInfo.type === "mcp" && (
+ <NodeSection title="MCP Configuration">
+ <div className="space-y-1">
+ <div className="text-sm py-1 px-2 bg-white rounded flex items-center gap-2">
+ <Package className="w-4 h-4 text-gray-500" />
+ <span>Dynamic Tools</span>
+ </div>
+ <div className="text-xs text-gray-600 p-2">
+ Tools provided by{" "}
+ {
+ (component as Component<McpWorkbenchConfig>).config
+ .server_params.type
+ }{" "}
+ server
+ </div>
+ </div>
+ </NodeSection>
+ )}
+ </BaseNode>
+ );
+});
+
+WorkbenchNode.displayName = "WorkbenchNode";
+
// Export all node types
export const nodeTypes = {
team: TeamNode,
agent: AgentNode,
+ workbench: WorkbenchNode,
};
const EDGE_STYLES = {
"model-connection": { stroke: "rgb(220,220,220)" },
"tool-connection": { stroke: "rgb(220,220,220)" },
+ "workbench-connection": { stroke: "rgb(34, 197, 94)" }, // Green for workbench connections
"agent-connection": { stroke: "rgb(220,220,220)" },
"termination-connection": { stroke: "rgb(220,220,220)" },
} as const;
@@ -495,6 +721,7 @@ export const CustomEdge = ({
export const edgeTypes = {
"model-connection": CustomEdge,
"tool-connection": CustomEdge,
+ "workbench-connection": CustomEdge,
"agent-connection": CustomEdge,
"termination-connection": CustomEdge,
};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/store.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/store.tsx
index 0c2791e9c..6fb1ca05c 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/store.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/store.tsx
@@ -12,25 +12,46 @@ import {
TeamConfig,
AgentConfig,
ToolConfig,
+ WorkbenchConfig,
+ StaticWorkbenchConfig,
Component,
ComponentConfig,
} from "../../../types/datamodel";
import {
convertTeamConfigToGraph,
getLayoutedElements,
+ updateNodeDimensions,
getUniqueName,
} from "./utils";
+import {
+ markNodeAsUserPositioned,
+ clearUserPositionedFlags,
+ generateComponentKey,
+} from "./layout-storage";
import {
isTeamComponent,
isAgentComponent,
isToolComponent,
+ isWorkbenchComponent,
isTerminationComponent,
isModelComponent,
isSelectorTeam,
isAssistantAgent,
isWebSurferAgent,
+ isStaticWorkbench,
} from "../../../types/guards";
+// Helper function to normalize workbench format (handle both single object and array)
+const normalizeWorkbenches = (
+ workbench:
+ | Component<WorkbenchConfig>[]
+ | Component<WorkbenchConfig>
+ | undefined
+): Component<WorkbenchConfig>[] => {
+ if (!workbench) return [];
+ return Array.isArray(workbench) ? workbench : [workbench];
+};
+
const MAX_HISTORY = 50;
export interface TeamBuilderState {
@@ -40,6 +61,7 @@ export interface TeamBuilderState {
history: Array<{ nodes: CustomNode[]; edges: CustomEdge[] }>;
currentHistoryIndex: number;
originalComponent: Component<TeamConfig> | null;
+ teamId: string | null;
// Simplified actions
addNode: (
@@ -55,6 +77,7 @@ export interface TeamBuilderState {
removeEdge: (edgeId: string) => void;
setSelectedNode: (nodeId: string | null) => void;
+ setNodeUserPositioned: (nodeId: string, position: Position) => void;
undo: () => void;
redo: () => void;
@@ -63,7 +86,8 @@ export interface TeamBuilderState {
syncToJson: () => Component<TeamConfig> | null;
loadFromJson: (
config: Component<TeamConfig>,
- isInitialLoad?: boolean
+ isInitialLoad?: boolean,
+ teamId?: string
) => GraphState;
layoutNodes: () => void;
resetHistory: () => void;
@@ -102,6 +126,17 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({
history: [],
currentHistoryIndex: -1,
originalComponent: null,
+ teamId: null,
+
+ setNodeUserPositioned: (nodeId: string, position: Position) => {
+ const state = get();
+ if (state.teamId) {
+ const node = state.nodes.find((n) => n.id === nodeId);
+ if (node) {
+ markNodeAsUserPositioned(state.teamId, node, position);
+ }
+ }
+ },
addNode: (
position: Position,
@@ -157,17 +192,63 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({
isAgentComponent(targetNode.data.component) &&
isAssistantAgent(targetNode.data.component)
) {
- if (!targetNode.data.component.config.tools) {
- targetNode.data.component.config.tools = [];
+ // Get or create workbenches array
+ if (!targetNode.data.component.config.workbench) {
+ targetNode.data.component.config.workbench = [];
}
- const toolName = getUniqueName(
- clonedComponent.config.name || clonedComponent.label || "tool",
- targetNode.data.component.config.tools.map(
- (t) => t.config.name || t.label || "tool"
- )
+
+ let workbenches = normalizeWorkbenches(
+ targetNode.data.component.config.workbench
);
- clonedComponent.config.name = toolName;
- targetNode.data.component.config.tools.push(clonedComponent);
+
+ // Find existing StaticWorkbench or create one
+ let staticWorkbenchIndex = workbenches.findIndex((wb) =>
+ isStaticWorkbench(wb)
+ );
+
+ if (staticWorkbenchIndex === -1) {
+ // Create a new StaticWorkbench
+ const newWorkbench: Component<StaticWorkbenchConfig> = {
+ provider: "autogen_core.tools.StaticWorkbench",
+ component_type: "workbench",
+ version: 1,
+ component_version: 1,
+ config: {
+ tools: [],
+ },
+ label: "Static Workbench",
+ description: "A static workbench for managing custom tools",
+ };
+ workbenches = [...workbenches, newWorkbench];
+ targetNode.data.component.config.workbench = workbenches;
+ staticWorkbenchIndex = workbenches.length - 1;
+ }
+
+ // Type guard to ensure we have a StaticWorkbench (which supports tools)
+ const workbench = workbenches[staticWorkbenchIndex];
+ if (isStaticWorkbench(workbench)) {
+ const staticWorkbenchConfig =
+ workbench.config as StaticWorkbenchConfig;
+
+ // Ensure the workbench has tools array
+ if (!staticWorkbenchConfig.tools) {
+ staticWorkbenchConfig.tools = [];
+ }
+
+ // Generate unique tool name within the workbench
+ const toolName = getUniqueName(
+ clonedComponent.config.name || clonedComponent.label || "tool",
+ staticWorkbenchConfig.tools.map(
+ (t: Component<ToolConfig>) =>
+ t.config.name || t.label || "tool"
+ )
+ );
+ clonedComponent.config.name = toolName;
+
+ // Add tool to workbench
+ staticWorkbenchConfig.tools.push(clonedComponent);
+ }
+
return {
nodes: newNodes,
edges: newEdges,
@@ -200,6 +281,35 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({
return node;
});
+ return {
+ nodes: newNodes,
+ edges: newEdges,
+ history: [
+ ...state.history.slice(0, state.currentHistoryIndex + 1),
+ { nodes: newNodes, edges: newEdges },
+ ].slice(-MAX_HISTORY),
+ currentHistoryIndex: state.currentHistoryIndex + 1,
+ };
+ }
+ } else if (isWorkbenchComponent(clonedComponent)) {
+ if (
+ isAgentComponent(targetNode.data.component) &&
+ isAssistantAgent(targetNode.data.component)
+ ) {
+ // Initialize workbench array if needed
+ if (!targetNode.data.component.config.workbench) {
+ targetNode.data.component.config.workbench = [];
+ }
+
+ // Normalize to array format
+ let workbenches = normalizeWorkbenches(
+ targetNode.data.component.config.workbench
+ );
+
+ // Add the new workbench
+ workbenches.push(clonedComponent);
+ targetNode.data.component.config.workbench = workbenches;
+
return {
nodes: newNodes,
edges: newEdges,
@@ -279,10 +389,39 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({
);
}
}
+ } else if (isWorkbenchComponent(clonedComponent)) {
+ const newNode: CustomNode = {
+ id: nanoid(),
+ position,
+ type: clonedComponent.component_type,
+ data: {
+ label: clonedComponent.label || "Workbench",
+ component: clonedComponent,
+ type: clonedComponent.component_type as NodeData["type"],
+ },
+ };
+ newNodes.push(newNode);
+ }
+
+ // For adding components to existing nodes (tools, models, etc.),
+ // only update dimensions to preserve user positioning
+ if (targetNodeId) {
+ const { nodes: updatedNodes, edges: updatedEdges } =
+ updateNodeDimensions(newNodes, newEdges);
+ return {
+ nodes: updatedNodes,
+ edges: updatedEdges,
+ history: [
+ ...state.history.slice(0, state.currentHistoryIndex + 1),
+ { nodes: updatedNodes, edges: updatedEdges },
+ ].slice(-MAX_HISTORY),
+ currentHistoryIndex: state.currentHistoryIndex + 1,
+ };
}
+ // For new team/agent nodes, use full layout
const { nodes: layoutedNodes, edges: layoutedEdges } =
- getLayoutedElements(newNodes, newEdges);
+ getLayoutedElements(newNodes, newEdges, state.teamId || undefined);
return {
nodes: layoutedNodes,
@@ -504,32 +643,41 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({
},
layoutNodes: () => {
- const { nodes, edges } = get();
+ const state = get();
+ // Clear user-positioned flags for full layout
+ if (state.teamId) {
+ clearUserPositionedFlags(state.teamId);
+ }
+
const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(
- nodes,
- edges
+ state.nodes,
+ state.edges,
+ state.teamId || undefined,
+ false // Don't preserve user positions for manual layout
);
set({
nodes: layoutedNodes,
edges: layoutedEdges,
history: [
- ...get().history.slice(0, get().currentHistoryIndex + 1),
+ ...state.history.slice(0, state.currentHistoryIndex + 1),
{ nodes: layoutedNodes, edges: layoutedEdges },
].slice(-MAX_HISTORY),
- currentHistoryIndex: get().currentHistoryIndex + 1,
+ currentHistoryIndex: state.currentHistoryIndex + 1,
});
},
loadFromJson: (
config: Component<TeamConfig>,
- isInitialLoad: boolean = true
+ isInitialLoad: boolean = true,
+ teamId?: string
) => {
// Get graph representation of team config
- const { nodes, edges } = convertTeamConfigToGraph(config);
+ const { nodes, edges } = convertTeamConfigToGraph(config, teamId);
const { nodes: layoutedNodes, edges: layoutedEdges } = getLayoutedElements(
nodes,
- edges
+ edges,
+ teamId
);
if (isInitialLoad) {
@@ -538,6 +686,7 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({
nodes: layoutedNodes,
edges: layoutedEdges,
originalComponent: config,
+ teamId: teamId || null,
history: [{ nodes: layoutedNodes, edges: layoutedEdges }],
currentHistoryIndex: 0,
selectedNodeId: null,
@@ -552,6 +701,7 @@ export const useTeamBuilderStore = create<TeamBuilderState>((set, get) => ({
set((state) => ({
nodes: layoutedNodes,
edges: layoutedEdges,
+ teamId: teamId || state.teamId,
history: [
...state.history.slice(0, state.currentHistoryIndex + 1),
{ nodes: layoutedNodes, edges: layoutedEdges },
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/types.ts b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/types.ts
index d767bc29f..814842b4e 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/types.ts
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/types.ts
@@ -8,6 +8,7 @@ import {
export interface NodeData extends Record<string, unknown> {
component: Component<ComponentConfig>;
+ isUserPositioned?: boolean;
}
export interface EditingState {
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/utils.ts b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/utils.ts
index 0196217f0..40653b3ee 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/utils.ts
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/builder/utils.ts
@@ -9,8 +9,15 @@ import {
isAssistantAgent,
isUserProxyAgent,
isWebSurferAgent,
+ isStaticWorkbench,
+ isMcpWorkbench,
} from "../../../types/guards";
import { CustomNode, CustomEdge } from "./types";
+import {
+ getStoredPosition,
+ generateComponentKey,
+ isComponentUserPositioned,
+} from "./layout-storage";
interface Position {
x: number;
@@ -82,12 +89,34 @@ const calculateNodeHeight = (component: Component<ComponentConfig>): number => {
// Only AssistantAgent has model_client and tools
if (isAssistantAgent(component)) {
height += 200;
- // Add height for tools section and items
- if (component.config.tools?.length) {
- height += LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_SECTION;
- height +=
- component.config.tools.length *
- LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_ITEM;
+ // Add height for workbench section if present
+ const workbenchConfig = component.config.workbench;
+ if (workbenchConfig) {
+ // Handle both single workbench object and array of workbenches
+ const workbenches = Array.isArray(workbenchConfig)
+ ? workbenchConfig
+ : [workbenchConfig];
+
+ if (workbenches.length > 0) {
+ // Add height for workbench section header
+ height += LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_SECTION;
+
+ // Calculate total height for all workbenches
+ workbenches.forEach((workbench) => {
+ if (!workbench) return;
+
+ if (isStaticWorkbench(workbench)) {
+ // StaticWorkbench: count individual tools
+ const toolCount = workbench.config.tools?.length || 0;
+ if (toolCount > 0) {
+ height += toolCount * LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_ITEM;
+ }
+ } else if (isMcpWorkbench(workbench)) {
+ // MCP workbench: add standard height for dynamic tools display
+ height += LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_ITEM;
+ }
+ });
+ }
}
}
if (isWebSurferAgent(component)) {
@@ -99,6 +128,22 @@ const calculateNodeHeight = (component: Component<ComponentConfig>): number => {
}
break;
+
+ case "workbench":
+ // Add height for workbench content
+ if (isStaticWorkbench(component)) {
+ // StaticWorkbench: show tools
+ const toolCount = component.config.tools?.length || 0;
+ height += LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_SECTION;
+ if (toolCount > 0) {
+ height += toolCount * LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_ITEM;
+ }
+ } else if (isMcpWorkbench(component)) {
+ // MCP workbench: show server configuration
+ height += LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_SECTION;
+ height += LAYOUT_CONFIG.CONTENT_HEIGHTS.TOOL_ITEM; // For server info display
+ }
+ break;
}
return Math.max(height, LAYOUT_CONFIG.NODE.MIN_HEIGHT);
@@ -166,6 +211,16 @@ const createNode = (
},
});
+// Get position for a component, checking storage first
+const getPositionForComponent = (
+ teamId: string,
+ component: Component<ComponentConfig>,
+ fallbackPosition: Position
+): Position => {
+ const stored = getStoredPosition(teamId, component);
+ return stored?.position || fallbackPosition;
+};
+
// Helper to create edges with consistent structure
const createEdge = (
source: string,
@@ -182,7 +237,8 @@ const createEdge = (
// Convert team configuration to graph structure with dynamic layout
export const convertTeamConfigToGraph = (
- teamComponent: Component<TeamConfig>
+ teamComponent: Component<TeamConfig>,
+ teamId?: string
): { nodes: CustomNode[]; edges: CustomEdge[] } => {
const nodes: CustomNode[] = [];
const edges: CustomEdge[] = [];
@@ -190,13 +246,20 @@ export const convertTeamConfigToGraph = (
// Create agent nodes first to calculate their positions
const agentNodes: CustomNode[] = [];
teamComponent.config.participants.forEach((participant, index) => {
- const position = calculateAgentPosition(index, agentNodes);
+ const calculatedPosition = calculateAgentPosition(index, agentNodes);
+ const position = teamId
+ ? getPositionForComponent(teamId, participant, calculatedPosition)
+ : calculatedPosition;
const agentNode = createNode(position, participant);
agentNodes.push(agentNode);
});
// Create team node with position based on agent positions
- const teamNode = createNode(calculateTeamPosition(agentNodes), teamComponent);
+ const calculatedTeamPosition = calculateTeamPosition(agentNodes);
+ const teamPosition = teamId
+ ? getPositionForComponent(teamId, teamComponent, calculatedTeamPosition)
+ : calculatedTeamPosition;
+ const teamNode = createNode(teamPosition, teamComponent);
// Add all nodes and create edges
nodes.push(teamNode, ...agentNodes);
@@ -210,7 +273,9 @@ export const convertTeamConfigToGraph = (
// Layout existing nodes with dynamic heights
export const getLayoutedElements = (
nodes: CustomNode[],
- edges: CustomEdge[]
+ edges: CustomEdge[],
+ teamId?: string,
+ preserveUserPositions: boolean = true
): { nodes: CustomNode[]; edges: CustomEdge[] } => {
// Find team node and agent nodes
const teamNode = nodes.find((n) => n.data.type === "team");
@@ -219,22 +284,57 @@ export const getLayoutedElements = (
const agentNodes = nodes.filter((n) => n.data.type !== "team");
// Calculate new positions for agent nodes
- const layoutedAgentNodes = agentNodes.map((node, index) => ({
- ...node,
- position: calculateAgentPosition(index, agentNodes.slice(0, index)),
- data: {
- ...node.data,
- dimensions: {
- width: LAYOUT_CONFIG.NODE.WIDTH,
- height: calculateNodeHeight(node.data.component),
+ const layoutedAgentNodes = agentNodes.map((node, index) => {
+ const calculatedPosition = calculateAgentPosition(
+ index,
+ agentNodes.slice(0, index)
+ );
+
+ // Check if we should preserve user position
+ const shouldPreservePosition =
+ preserveUserPositions &&
+ teamId &&
+ isComponentUserPositioned(teamId, node.data.component);
+
+ const position = shouldPreservePosition
+ ? node.position
+ : teamId
+ ? getPositionForComponent(teamId, node.data.component, calculatedPosition)
+ : calculatedPosition;
+
+ return {
+ ...node,
+ position,
+ data: {
+ ...node.data,
+ dimensions: {
+ width: LAYOUT_CONFIG.NODE.WIDTH,
+ height: calculateNodeHeight(node.data.component),
+ },
},
- },
- }));
+ };
+ });
// Update team node position
+ const calculatedTeamPosition = calculateTeamPosition(layoutedAgentNodes);
+ const shouldPreserveTeamPosition =
+ preserveUserPositions &&
+ teamId &&
+ isComponentUserPositioned(teamId, teamNode.data.component);
+
+ const teamPosition = shouldPreserveTeamPosition
+ ? teamNode.position
+ : teamId
+ ? getPositionForComponent(
+ teamId,
+ teamNode.data.component,
+ calculatedTeamPosition
+ )
+ : calculatedTeamPosition;
+
const layoutedTeamNode = {
...teamNode,
- position: calculateTeamPosition(layoutedAgentNodes),
+ position: teamPosition,
data: {
...teamNode.data,
dimensions: {
@@ -250,6 +350,28 @@ export const getLayoutedElements = (
};
};
+// Update only node dimensions without changing positions
+export const updateNodeDimensions = (
+ nodes: CustomNode[],
+ edges: CustomEdge[]
+): { nodes: CustomNode[]; edges: CustomEdge[] } => {
+ const updatedNodes = nodes.map((node) => ({
+ ...node,
+ data: {
+ ...node.data,
+ dimensions: {
+ width: LAYOUT_CONFIG.NODE.WIDTH,
+ height: calculateNodeHeight(node.data.component),
+ },
+ },
+ }));
+
+ return {
+ nodes: updatedNodes,
+ edges,
+ };
+};
+
// Generate unique names (unchanged)
export const getUniqueName = (
baseName: string,
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/hooks.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/hooks.tsx
deleted file mode 100644
index 8079a6068..000000000
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/hooks.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { config } from "process";
-import { Team } from "../../types/datamodel";
-
-export const useTeam = (team: Team) => {
- return {
- id: team.id,
- name: team.config.config.name,
- type: team.config.config.team_type,
- participants: team.config.config.participants,
- updated: team.updated_at,
- config: team.config,
-
- // Helper methods
- setName: (name: string) => {
- team.config.config.name = name;
- },
-
- // Computed properties
- agentCount: team.config.config.participants.length,
-
- // Type guards
- isRoundRobin: () => team.config.config.team_type === "RoundRobinGroupChat",
- isSelector: () => team.config.config.team_type === "SelectorGroupChat",
- };
-};
-
-// For creating new teams
-export const useTeamCreation = () => {
- const createTeamName = () => `new_team_${new Date().getTime()}`;
-
- return {
- createTeamName,
- initNewTeam: (baseTeam: Team) => {
- const team = Object.assign({}, baseTeam);
- team.config.config.name = createTeamName();
- return team;
- },
- };
-};
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/manager.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/manager.tsx
index 0ecf9e54f..52e0803d1 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/manager.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/manager.tsx
@@ -7,6 +7,7 @@ import { useGalleryStore } from "../gallery/store";
import { TeamSidebar } from "./sidebar";
import { Gallery, type Team } from "../../types/datamodel";
import { TeamBuilder } from "./builder/builder";
+import { clearTeamLayoutStorage } from "./builder/layout-storage";
export const TeamManager: React.FC = () => {
const [isLoading, setIsLoading] = useState(false);
@@ -101,6 +102,10 @@ export const TeamManager: React.FC = () => {
try {
await teamAPI.deleteTeam(teamId, user.id);
+
+ // Clear layout storage for this team
+ clearTeamLayoutStorage(teamId.toString());
+
setTeams(teams.filter((t) => t.id !== teamId));
if (currentTeam?.id === teamId) {
setCurrentTeam(null);
diff --git a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/sidebar.tsx b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/sidebar.tsx
index 42fd06d43..073c9f644 100644
--- a/python/packages/autogen-studio/frontend/src/components/views/teambuilder/sidebar.tsx
+++ b/python/packages/autogen-studio/frontend/src/components/views/teambuilder/sidebar.tsx
@@ -244,7 +244,7 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
>
{/* Team Name and Actions Row */}
<div className="flex items-center justify-between">
- <span className="font-medium truncate">
+ <span className="font-medium truncate text-sm">
{team.component?.label}
</span>
<div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
@@ -272,8 +272,9 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
<div className="flex items-center gap-1">
<Bot className="w-3 h-3" />
<span>
- {team.component.config.participants.length}{" "}
- {team.component.config.participants.length === 1
+ {team.component.config?.participants?.length || 0}{" "}
+ {(team.component.config?.participants?.length ||
+ 0) === 1
? "agent"
: "agents"}
</span>
@@ -332,16 +333,16 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
{selectedGallery?.config.components?.teams.map((galleryTeam) => (
<div
key={galleryTeam.label + galleryTeam.component_type}
- className="relative border-secondary"
+ className="relative border-secondary -ml-2 group"
>
<div
className={`absolute top-1 left-0.5 z-50 h-[calc(100%-8px)]
- w-1 bg-opacity-80 rounded bg-tertiary`}
+ w-1 bg-opacity-80 rounded bg-tertiary group-hover:bg-accent`}
/>
<div className="group ml-1 flex flex-col p-3 rounded-l cursor-pointer hover:bg-secondary">
{/* Team Name and Use Template Action */}
<div className="flex items-center justify-between">
- <span className="font-medium truncate">
+ <span className="font-medium truncate text-sm">
{galleryTeam.label}
</span>
<div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
@@ -380,8 +381,8 @@ export const TeamSidebar: React.FC<TeamSidebarProps> = ({
<div className="flex items-center gap-1">
<Bot className="w-3 h-3" />
<span>
- {galleryTeam.config.participants.length}{" "}
- {galleryTeam.config.participants.length === 1
+ {galleryTeam.config?.participants?.length || 0}{" "}
+ {(galleryTeam.config?.participants?.length || 0) === 1
? "agent"
: "agents"}
</span>
diff --git a/python/packages/autogen-studio/frontend/src/hooks/store.tsx b/python/packages/autogen-studio/frontend/src/hooks/store.tsx
index 107ce7e20..b9cc23ff0 100644
--- a/python/packages/autogen-studio/frontend/src/hooks/store.tsx
+++ b/python/packages/autogen-studio/frontend/src/hooks/store.tsx
@@ -6,6 +6,7 @@ import { Message, Session } from "../components/types/datamodel";
interface IBreadcrumb {
name: string;
href: string;
+ icon?: React.ReactNode;
current?: boolean;
}
diff --git a/python/packages/autogen-studio/frontend/src/pages/lite.tsx b/python/packages/autogen-studio/frontend/src/pages/lite.tsx
new file mode 100644
index 000000000..217ad164a
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/pages/lite.tsx
@@ -0,0 +1,39 @@
+import * as React from "react";
+import { graphql } from "gatsby";
+
+import { SessionManager } from "../components/views/playground/manager";
+import { LiteLayout } from "../components/layout";
+
+// markup
+const LitePage = ({ data }: any) => {
+ return (
+ <LiteLayout>
+ <main style={{ height: "100%" }} className="h-full">
+ <SessionManager />
+ </main>
+ </LiteLayout>
+ );
+};
+
+export const query = graphql`
+ query LitePageQuery {
+ site {
+ siteMetadata {
+ description
+ title
+ }
+ }
+ }
+`;
+
+export default LitePage;
+
+export const Head = () => (
+ <>
+ <title>AutoGen Studio - Lite Mode</title>
+ <meta
+ name="description"
+ content="AutoGen Studio Lite Mode - Simplified chat interface"
+ />
+ </>
+);
diff --git a/python/packages/autogen-studio/frontend/src/pages/mcp.tsx b/python/packages/autogen-studio/frontend/src/pages/mcp.tsx
new file mode 100644
index 000000000..43a6e8ad4
--- /dev/null
+++ b/python/packages/autogen-studio/frontend/src/pages/mcp.tsx
@@ -0,0 +1,28 @@
+import * as React from "react";
+import Layout from "../components/layout";
+import { graphql } from "gatsby";
+import McpManager from "../components/views/mcp/manager";
+
+// markup
+const McpPage = ({ data }: any) => {
+ return (
+ <Layout meta={data.site.siteMetadata} title="MCP Playground" link={"/mcp"}>
+ <main style={{ height: "100%" }} className="h-full">
+ <McpManager />
+ </main>
+ </Layout>
+ );
+};
+
+export const query = graphql`
+ query McpPageQuery {
+ site {
+ siteMetadata {
+ description
+ title
+ }
+ }
+ }
+`;
+
+export default McpPage;
diff --git a/python/packages/autogen-studio/notebooks/team.json b/python/packages/autogen-studio/notebooks/team.json
index bcd3d6696..8ad5f6359 100644
--- a/python/packages/autogen-studio/notebooks/team.json
+++ b/python/packages/autogen-studio/notebooks/team.json
@@ -4,15 +4,15 @@
"version": 1,
"component_version": 1,
"description": "A single AssistantAgent (with a calculator tool) in a RoundRobinGroupChat team. ",
- "label": "default_team17",
+ "label": "RoundRobin Team",
"config": {
"participants": [
{
"provider": "autogen_agentchat.agents.AssistantAgent",
"component_type": "agent",
- "version": 1,
- "component_version": 1,
- "description": "An agent that provides assistance with tool use.",
+ "version": 2,
+ "component_version": 2,
+ "description": "An agent that provides assistance with tool use.\n The :meth:`on_messages` returns a :class:`~autogen_agentchat.base.Response`\n in which :attr:`~autogen_agentchat.base.Response.chat_message` is the final\n response message.",
"label": "AssistantAgent",
"config": {
"name": "assistant_agent",
@@ -27,24 +27,35 @@
"model": "gpt-4o-mini"
}
},
- "tools": [
+ "workbench": [
{
- "provider": "autogen_core.tools.FunctionTool",
- "component_type": "tool",
+ "provider": "autogen_core.tools.StaticStreamWorkbench",
+ "component_type": "workbench",
"version": 1,
"component_version": 1,
- "description": "Create custom tools by wrapping standard Python functions.",
- "label": "FunctionTool",
+ "description": "A workbench that provides a static set of tools that do not change after\n each tool execution, and supports streaming results.",
+ "label": "StaticStreamWorkbench",
"config": {
- "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
- "name": "calculator",
- "description": "A simple calculator that performs basic arithmetic operations",
- "global_imports": [],
- "has_cancellation_support": false
+ "tools": [
+ {
+ "provider": "autogen_core.tools.FunctionTool",
+ "component_type": "tool",
+ "version": 1,
+ "component_version": 1,
+ "description": "Create custom tools by wrapping standard Python functions.",
+ "label": "FunctionTool",
+ "config": {
+ "source_code": "def calculator(a: float, b: float, operator: str) -> str:\n try:\n if operator == \"+\":\n return str(a + b)\n elif operator == \"-\":\n return str(a - b)\n elif operator == \"*\":\n return str(a * b)\n elif operator == \"/\":\n if b == 0:\n return \"Error: Division by zero\"\n return str(a / b)\n else:\n return \"Error: Invalid operator. Please use +, -, *, or /\"\n except Exception as e:\n return f\"Error: {str(e)}\"\n",
+ "name": "calculator",
+ "description": "A simple calculator that performs basic arithmetic operations",
+ "global_imports": [],
+ "has_cancellation_support": false
+ }
+ }
+ ]
}
}
],
- "handoffs": [],
"model_context": {
"provider": "autogen_core.model_context.UnboundedChatCompletionContext",
"component_type": "chat_completion_context",
@@ -58,7 +69,9 @@
"system_message": "You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.",
"model_client_stream": false,
"reflect_on_tool_use": false,
- "tool_call_summary_format": "{result}"
+ "tool_call_summary_format": "{result}",
+ "max_tool_iterations": 1,
+ "metadata": {}
}
}
],
@@ -89,11 +102,13 @@
"description": "Terminate the conversation after a maximum number of messages have been exchanged.",
"label": "MaxMessageTermination",
"config": {
- "max_messages": 10
+ "max_messages": 10,
+ "include_agent_event": false
}
}
]
}
- }
+ },
+ "emit_team_events": false
}
}
diff --git a/python/packages/autogen-studio/notebooks/tutorial.ipynb b/python/packages/autogen-studio/notebooks/tutorial.ipynb
index ea0509951..25d3c86be 100644
--- a/python/packages/autogen-studio/notebooks/tutorial.ipynb
+++ b/python/packages/autogen-studio/notebooks/tutorial.ipynb
@@ -16,28 +16,9 @@
},
{
"cell_type": "code",
- "execution_count": 1,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "/Users/victordibia/projects/hax/autogen/python/packages/autogen-core/src/autogen_core/_component_config.py:252: UserWarning: \n",
- "⚠️ SECURITY WARNING ⚠️\n",
- "Loading a FunctionTool from config will execute code to import the provided global imports and and function code.\n",
- "Only load configs from TRUSTED sources to prevent arbitrary code execution.\n",
- " instance = component_class._from_config(validated_config) # type: ignore\n"
- ]
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "task_result=TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, content='What is the weather in New York?', type='TextMessage'), TextMessage(source='assistant_agent', models_usage=RequestUsage(prompt_tokens=86, completion_tokens=47), metadata={}, content=\"I'm unable to provide real-time weather information. I recommend checking a reliable weather website or app for the current weather in New York. If you have any other questions or need assistance with a different topic, feel free to ask!\", type='TextMessage'), TextMessage(source='assistant_agent', models_usage=RequestUsage(prompt_tokens=138, completion_tokens=5), metadata={}, content='TERMINATE', type='TextMessage')], stop_reason=\"Text 'TERMINATE' mentioned\") usage='' duration=1.734266996383667\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"from autogenstudio.teammanager import TeamManager\n",
"\n",
@@ -48,28 +29,22 @@
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "source='user' models_usage=None metadata={} content='What is the weather in New York?' type='TextMessage'\n",
- "source='assistant_agent' models_usage=RequestUsage(prompt_tokens=86, completion_tokens=34) metadata={} content=\"I currently don't have access to real-time weather data. You can check a reliable weather website or application for the most current information about the weather in New York.\" type='TextMessage'\n",
- "source='llm_call_event' models_usage=None metadata={} content='{\"type\": \"LLMCall\", \"messages\": [{\"content\": \"You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.\", \"role\": \"system\"}, {\"content\": \"What is the weather in New York?\", \"role\": \"user\", \"name\": \"user\"}], \"response\": {\"id\": \"chatcmpl-B76eHFx8OqWQlbnNaK3W6CJtuznmR\", \"choices\": [{\"finish_reason\": \"stop\", \"index\": 0, \"logprobs\": null, \"message\": {\"content\": \"I currently don\\'t have access to real-time weather data. You can check a reliable weather website or application for the most current information about the weather in New York.\", \"refusal\": null, \"role\": \"assistant\", \"audio\": null, \"function_call\": null, \"tool_calls\": null}}], \"created\": 1741033553, \"model\": \"gpt-4o-mini-2024-07-18\", \"object\": \"chat.completion\", \"service_tier\": \"default\", \"system_fingerprint\": \"fp_06737a9306\", \"usage\": {\"completion_tokens\": 34, \"prompt_tokens\": 86, \"total_tokens\": 120, \"completion_tokens_details\": {\"accepted_prediction_tokens\": 0, \"audio_tokens\": 0, \"reasoning_tokens\": 0, \"rejected_prediction_tokens\": 0}, \"prompt_tokens_details\": {\"audio_tokens\": 0, \"cached_tokens\": 0}}}, \"prompt_tokens\": 86, \"completion_tokens\": 34, \"agent_id\": \"assistant_agent/3db465b4-fb0a-4ffd-80df-f4554605d4c0\"}'\n",
- "source='assistant_agent' models_usage=RequestUsage(prompt_tokens=125, completion_tokens=5) metadata={} content='TERMINATE' type='TextMessage'\n",
- "source='llm_call_event' models_usage=None metadata={} content='{\"type\": \"LLMCall\", \"messages\": [{\"content\": \"You are a helpful assistant. Solve tasks carefully. When done, say TERMINATE.\", \"role\": \"system\"}, {\"content\": \"What is the weather in New York?\", \"role\": \"user\", \"name\": \"user\"}, {\"content\": \"I currently don\\'t have access to real-time weather data. You can check a reliable weather website or application for the most current information about the weather in New York.\", \"role\": \"assistant\", \"name\": \"assistant_agent\"}], \"response\": {\"id\": \"chatcmpl-B76eIpGDvd7M2nxdgezZuRzOJTQR1\", \"choices\": [{\"finish_reason\": \"stop\", \"index\": 0, \"logprobs\": null, \"message\": {\"content\": \"TERMINATE\", \"refusal\": null, \"role\": \"assistant\", \"audio\": null, \"function_call\": null, \"tool_calls\": null}}], \"created\": 1741033554, \"model\": \"gpt-4o-mini-2024-07-18\", \"object\": \"chat.completion\", \"service_tier\": \"default\", \"system_fingerprint\": \"fp_06737a9306\", \"usage\": {\"completion_tokens\": 5, \"prompt_tokens\": 125, \"total_tokens\": 130, \"completion_tokens_details\": {\"accepted_prediction_tokens\": 0, \"audio_tokens\": 0, \"reasoning_tokens\": 0, \"rejected_prediction_tokens\": 0}, \"prompt_tokens_details\": {\"audio_tokens\": 0, \"cached_tokens\": 0}}}, \"prompt_tokens\": 125, \"completion_tokens\": 5, \"agent_id\": \"assistant_agent/3db465b4-fb0a-4ffd-80df-f4554605d4c0\"}'\n",
- "task_result=TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, content='What is the weather in New York?', type='TextMessage'), TextMessage(source='assistant_agent', models_usage=RequestUsage(prompt_tokens=86, completion_tokens=34), metadata={}, content=\"I currently don't have access to real-time weather data. You can check a reliable weather website or application for the most current information about the weather in New York.\", type='TextMessage'), TextMessage(source='assistant_agent', models_usage=RequestUsage(prompt_tokens=125, completion_tokens=5), metadata={}, content='TERMINATE', type='TextMessage')], stop_reason=\"Text 'TERMINATE' mentioned\") usage='' duration=1.1263680458068848\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"result_stream = wm.run_stream(task=\"What is the weather in New York?\", team_config=\"team.json\")\n",
"async for response in result_stream:\n",
" print(response)"
]
},
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
{
"cell_type": "markdown",
"metadata": {},
@@ -79,17 +54,9 @@
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "[<autogen_agentchat.agents._assistant_agent.AssistantAgent object at 0x1219d3850>]\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"import json \n",
"from autogen_agentchat.teams import BaseGroupChat\n",
@@ -109,32 +76,9 @@
},
{
"cell_type": "code",
- "execution_count": 15,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "\u001b[32m2025-03-03 12:36:12.391\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36mautogenstudio.database.db_manager\u001b[0m:\u001b[36minitialize_database\u001b[0m:\u001b[36m61\u001b[0m - \u001b[1mCreating database tables...\u001b[0m\n",
- "\u001b[32m2025-03-03 12:36:12.425\u001b[0m | \u001b[1mINFO \u001b[0m | \u001b[36mautogenstudio.database.schema_manager\u001b[0m:\u001b[36m_initialize_alembic\u001b[0m:\u001b[36m154\u001b[0m - \u001b[1mAlembic initialization complete\u001b[0m\n",
- "INFO [alembic.runtime.migration] Context impl SQLiteImpl.\n",
- "INFO [alembic.runtime.migration] Will assume non-transactional DDL.\n",
- "INFO [alembic.autogenerate.compare] Detected type change from NUMERIC() to UUID() on 'message.run_id'\n",
- "INFO [alembic.autogenerate.compare] Detected type change from NUMERIC() to UUID() on 'run.id'\n"
- ]
- },
- {
- "data": {
- "text/plain": [
- "Response(message='Database initialized successfully', status=True, data=None)"
- ]
- },
- "execution_count": 15,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
+ "outputs": [],
"source": [
"from autogenstudio.database import DatabaseManager\n",
"import os\n",
@@ -204,22 +148,9 @@
},
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "source='user' models_usage=None metadata={} content='Plan a 3 day trip to Nepal.' type='TextMessage'\n",
- "source='planner_agent' models_usage=RequestUsage(prompt_tokens=45, completion_tokens=64) metadata={} content='Sure, on your 3-day trip to Nepal, you could start by visiting historical landmarks and local markets in Kathmandu, hike for a day in the Annapurna region to experience breathtaking mountain views and end your trip by exploring the religious sites and wildlife in Lumbini and Chitwan respectively.' type='TextMessage'\n",
- "source='local_agent' models_usage=RequestUsage(prompt_tokens=125, completion_tokens=86) metadata={} content=\"Absolutely, on the first day, feel free to explore Kathmandu's rich history and culture, visit temples like Swayambhunath and Pashupatinath. On the second day, take a spectacular mountain flight to view Mount Everest and then head to Pokhara to engage in adventure activities or relax by Phewa Lake. On the third day, explore the biodiversity at Chitwan National Park.\" type='TextMessage'\n",
- "source='language_agent' models_usage=RequestUsage(prompt_tokens=241, completion_tokens=72) metadata={} content=\"While going through your itinerary, I don't see any specific strategies for dealing with language barriers. For Nepal, whilst Nepali is the most widely spoken language, English is understood by many, especially in urban areas and by those working in the travel and hospitality sectors. Carrying a phrasebook or using a translator app could be helpful in more rural areas.\" type='TextMessage'\n",
- "source='travel_summary_agent' models_usage=RequestUsage(prompt_tokens=336, completion_tokens=220) metadata={} content=\"Your 3-day trip to Nepal is as follows:\\n\\nDay 1: Begin in Kathmandu, exploring the city's rich history and culture. Visit temples such as Swayambhunath and Pashupatinath. Immerse yourself in local markets to experience the vibrant local life.\\n\\nDay 2: As an early bird, embark on a spectacular mountain flight to witness Mount Everest's grandeur, followed by a trip to Pokhara. In Pokhara, you have the opportunity to partake in thrilling adventure activities or unwind by the serene Phewa Lake.\\n\\nDay 3: Dedicate your last day to exploring the biodiversity at Chitwan National Park, which offers an enchanting wildlife experience.\\n\\nLanguage considerations: While a substantial number of people in urban Nepal understand and communicate in English, particularly those in the tourism sector, having a phrasebook or using a translator app can be beneficial in rural regions.\\n\\nThis comprehensive plan ensures that you will enjoy the diversity of cultural, scenic, and wildlife experiences that Nepal has to offer in a short period. TERMINATE.\" type='TextMessage'\n",
- "TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, content='Plan a 3 day trip to Nepal.', type='TextMessage'), TextMessage(source='planner_agent', models_usage=RequestUsage(prompt_tokens=45, completion_tokens=64), metadata={}, content='Sure, on your 3-day trip to Nepal, you could start by visiting historical landmarks and local markets in Kathmandu, hike for a day in the Annapurna region to experience breathtaking mountain views and end your trip by exploring the religious sites and wildlife in Lumbini and Chitwan respectively.', type='TextMessage'), TextMessage(source='local_agent', models_usage=RequestUsage(prompt_tokens=125, completion_tokens=86), metadata={}, content=\"Absolutely, on the first day, feel free to explore Kathmandu's rich history and culture, visit temples like Swayambhunath and Pashupatinath. On the second day, take a spectacular mountain flight to view Mount Everest and then head to Pokhara to engage in adventure activities or relax by Phewa Lake. On the third day, explore the biodiversity at Chitwan National Park.\", type='TextMessage'), TextMessage(source='language_agent', models_usage=RequestUsage(prompt_tokens=241, completion_tokens=72), metadata={}, content=\"While going through your itinerary, I don't see any specific strategies for dealing with language barriers. For Nepal, whilst Nepali is the most widely spoken language, English is understood by many, especially in urban areas and by those working in the travel and hospitality sectors. Carrying a phrasebook or using a translator app could be helpful in more rural areas.\", type='TextMessage'), TextMessage(source='travel_summary_agent', models_usage=RequestUsage(prompt_tokens=336, completion_tokens=220), metadata={}, content=\"Your 3-day trip to Nepal is as follows:\\n\\nDay 1: Begin in Kathmandu, exploring the city's rich history and culture. Visit temples such as Swayambhunath and Pashupatinath. Immerse yourself in local markets to experience the vibrant local life.\\n\\nDay 2: As an early bird, embark on a spectacular mountain flight to witness Mount Everest's grandeur, followed by a trip to Pokhara. In Pokhara, you have the opportunity to partake in thrilling adventure activities or unwind by the serene Phewa Lake.\\n\\nDay 3: Dedicate your last day to exploring the biodiversity at Chitwan National Park, which offers an enchanting wildlife experience.\\n\\nLanguage considerations: While a substantial number of people in urban Nepal understand and communicate in English, particularly those in the tourism sector, having a phrasebook or using a translator app can be beneficial in rural regions.\\n\\nThis comprehensive plan ensures that you will enjoy the diversity of cultural, scenic, and wildlife experiences that Nepal has to offer in a short period. TERMINATE.\", type='TextMessage')], stop_reason=\"Text 'TERMINATE' mentioned\")\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"result = group_chat.run_stream(task=\"Plan a 3 day trip to Nepal.\")\n",
"async for response in result:\n",
@@ -228,22 +159,9 @@
},
{
"cell_type": "code",
- "execution_count": 11,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "source='user' models_usage=None metadata={} content='Plan a 3 day trip to Nepal.' type='TextMessage'\n",
- "source='planner_agent' models_usage=RequestUsage(prompt_tokens=45, completion_tokens=74) metadata={} content='For a 3-day trip to Nepal, start your journey in Kathmandu, visit renowned UNESCO World Heritage Sites including Pashupatinath Temple and Boudhanath Stupa, day two explore the breathtaking city of Pokhara, and on the final day, hike the serene trails of Nagarkot to witness a captivating sunrise over the Himalayas.' type='TextMessage'\n",
- "source='local_agent' models_usage=RequestUsage(prompt_tokens=135, completion_tokens=57) metadata={} content='Immerse yourself in the local lifestyle by visiting the bustling markets of Kathmandu, explore the ancient, history-rich city of Bhaktapur, take a day hike to the breathtaking monasteries in the mountains and wrap it up with an unforgettable traditional Nepalese dinner.' type='TextMessage'\n",
- "source='language_agent' models_usage=RequestUsage(prompt_tokens=222, completion_tokens=34) metadata={} content='Consider packing a helpful language guide or translator app to communicate effectively with locals in Nepal since the primary language there is Nepali and not everyone might be fluent in English.' type='TextMessage'\n",
- "source='travel_summary_agent' models_usage=RequestUsage(prompt_tokens=279, completion_tokens=207) metadata={} content='Your final travel plan for a 3-day trip to Nepal is as follows:\\n\\nDay 1: Arrive in Kathmandu, immerse yourself in the local lifestyle by visiting the bustling markets, Pashupatinath Temple, and Boudhanath Stupa, all renowned UNESCO World Heritage Sites.\\n\\nDay 2: Explore the breathtaking city of Pokhara and the ancient, history-rich city of Bhaktapur. \\n\\nDay 3: Hike the serene trails of Nagarkot to witness a captivating sunrise over the Himalayas, take a day hike to the breathtaking monasteries in the mountains.\\n\\nThroughout your journey, engage with locals and enjoy a traditional Nepalese dinner. As the primary language in Nepal is Nepali, consider packing a helpful language guide or translator app to communicate effectively.\\n\\nEnsure your plan is flexible to accommodate for any unexpected changes or opportunities that present themselves while exploring the wonders of Nepal, remembering that the essence of travel is to appreciate the journey as much as the destination.\\n\\nTERMINATE' type='TextMessage'\n",
- "TaskResult(messages=[TextMessage(source='user', models_usage=None, metadata={}, content='Plan a 3 day trip to Nepal.', type='TextMessage'), TextMessage(source='planner_agent', models_usage=RequestUsage(prompt_tokens=45, completion_tokens=74), metadata={}, content='For a 3-day trip to Nepal, start your journey in Kathmandu, visit renowned UNESCO World Heritage Sites including Pashupatinath Temple and Boudhanath Stupa, day two explore the breathtaking city of Pokhara, and on the final day, hike the serene trails of Nagarkot to witness a captivating sunrise over the Himalayas.', type='TextMessage'), TextMessage(source='local_agent', models_usage=RequestUsage(prompt_tokens=135, completion_tokens=57), metadata={}, content='Immerse yourself in the local lifestyle by visiting the bustling markets of Kathmandu, explore the ancient, history-rich city of Bhaktapur, take a day hike to the breathtaking monasteries in the mountains and wrap it up with an unforgettable traditional Nepalese dinner.', type='TextMessage'), TextMessage(source='language_agent', models_usage=RequestUsage(prompt_tokens=222, completion_tokens=34), metadata={}, content='Consider packing a helpful language guide or translator app to communicate effectively with locals in Nepal since the primary language there is Nepali and not everyone might be fluent in English.', type='TextMessage'), TextMessage(source='travel_summary_agent', models_usage=RequestUsage(prompt_tokens=279, completion_tokens=207), metadata={}, content='Your final travel plan for a 3-day trip to Nepal is as follows:\\n\\nDay 1: Arrive in Kathmandu, immerse yourself in the local lifestyle by visiting the bustling markets, Pashupatinath Temple, and Boudhanath Stupa, all renowned UNESCO World Heritage Sites.\\n\\nDay 2: Explore the breathtaking city of Pokhara and the ancient, history-rich city of Bhaktapur. \\n\\nDay 3: Hike the serene trails of Nagarkot to witness a captivating sunrise over the Himalayas, take a day hike to the breathtaking monasteries in the mountains.\\n\\nThroughout your journey, engage with locals and enjoy a traditional Nepalese dinner. As the primary language in Nepal is Nepali, consider packing a helpful language guide or translator app to communicate effectively.\\n\\nEnsure your plan is flexible to accommodate for any unexpected changes or opportunities that present themselves while exploring the wonders of Nepal, remembering that the essence of travel is to appreciate the journey as much as the destination.\\n\\nTERMINATE', type='TextMessage')], stop_reason=\"Text 'TERMINATE' mentioned\")\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"import json\n",
"\n",
@@ -263,6 +181,13 @@
"async for response in result:\n",
" print(response)"
]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
}
],
"metadata": {
diff --git a/python/packages/autogen-studio/pyproject.toml b/python/packages/autogen-studio/pyproject.toml
index 1b567f5a1..d03f95e1f 100644
--- a/python/packages/autogen-studio/pyproject.toml
+++ b/python/packages/autogen-studio/pyproject.toml
@@ -34,8 +34,9 @@ dependencies = [
"html2text",
"autogen-core>=0.4.9.2,<0.7",
"autogen-agentchat>=0.4.9.2,<0.7",
- "autogen-ext[magentic-one, openai, azure]>=0.4.2,<0.7",
+ "autogen-ext[magentic-one, openai, azure, mcp]>=0.4.2,<0.7",
"anthropic",
+ "mcp>=1.11.0"
]
optional-dependencies = {web = ["fastapi", "uvicorn"], database = ["psycopg"]}
@@ -62,6 +63,8 @@ filterwarnings = [
"ignore:Deprecated call to `pkg_resources\\.declare_namespace\\('.*'\\):DeprecationWarning",
"ignore::DeprecationWarning:google.rpc",
]
+asyncio_mode = "auto"
+asyncio_default_fixture_loop_scope = "function"
[project.urls]
diff --git a/python/packages/autogen-studio/tests/mcp/test_mcp_callbacks.py b/python/packages/autogen-studio/tests/mcp/test_mcp_callbacks.py
new file mode 100644
index 000000000..414bd6d52
--- /dev/null
+++ b/python/packages/autogen-studio/tests/mcp/test_mcp_callbacks.py
@@ -0,0 +1,270 @@
+#!/usr/bin/env python3
+"""Test the refactored MCP callback functions"""
+
+import asyncio
+import pytest
+import uuid
+from unittest.mock import AsyncMock, MagicMock, patch
+from datetime import datetime, timezone
+
+from typing import Any
+
+from mcp.types import (
+ CreateMessageRequestParams,
+ CreateMessageResult,
+ ElicitRequestParams,
+ ElicitResult,
+ ErrorData,
+ TextContent
+)
+from mcp.shared.context import RequestContext
+
+from autogenstudio.mcp.callbacks import (
+ create_message_handler,
+ create_sampling_callback,
+ create_elicitation_callback
+)
+from autogenstudio.mcp.wsbridge import MCPWebSocketBridge
+
+
+class MockBridge(MCPWebSocketBridge):
+ """Mock bridge for testing callbacks"""
+
+ def __init__(self):
+ # Don't call parent __init__ to avoid WebSocket dependency
+ self.session_id = "test-session"
+ self.pending_elicitations = {}
+ self.events = []
+
+ async def on_mcp_activity(self, activity_type: str, message: str, details: dict) -> None:
+ self.events.append(("mcp_activity", activity_type, message, details))
+
+ async def on_elicitation_request(self, request_id: str, message: str, requested_schema: Any) -> None:
+ self.events.append(("elicitation_request", request_id, message, requested_schema))
+
+
+class TestMCPCallbacks:
+ """Test MCP callback functions"""
+
+ @pytest.fixture
+ def mock_bridge(self):
+ """Create a mock bridge"""
+ return MockBridge()
+
+ @pytest.mark.asyncio
+ async def test_message_handler_with_exception(self, mock_bridge):
+ """Test message handler with exception"""
+ handler = create_message_handler(mock_bridge)
+
+ test_exception = Exception("Test protocol error")
+ await handler(test_exception)
+
+ # Verify activity was logged
+ assert len(mock_bridge.events) == 1
+ event = mock_bridge.events[0]
+ assert event[0] == "mcp_activity"
+ assert event[1] == "error"
+ assert "Protocol error" in event[2]
+ assert "Test protocol error" in event[3]["details"]
+
+ @pytest.mark.asyncio
+ async def test_message_handler_with_method_message(self, mock_bridge):
+ """Test message handler with method-based message"""
+ handler = create_message_handler(mock_bridge)
+
+ # Create a mock message with method attribute
+ mock_message = MagicMock()
+ mock_message.method = "notifications/initialized"
+ mock_message.params = {"capabilities": {"tools": True}}
+
+ await handler(mock_message)
+
+ # Verify activity was logged
+ assert len(mock_bridge.events) == 1
+ event = mock_bridge.events[0]
+ assert event[0] == "mcp_activity"
+ assert event[1] == "protocol"
+ assert "notifications/initialized" in event[2]
+ assert event[3]["method"] == "notifications/initialized"
+
+ @pytest.mark.asyncio
+ async def test_message_handler_with_other_message(self, mock_bridge):
+ """Test message handler with other message types"""
+ handler = create_message_handler(mock_bridge)
+
+ # Create a simple mock message without method, avoiding recursion issues
+ class SimpleMockMessage:
+ def model_dump(self):
+ return {"type": "response", "data": "test"}
+
+ mock_message = SimpleMockMessage()
+
+ # Type ignore for test purposes - we're testing edge case handling
+ await handler(mock_message) # type: ignore
+
+ # Verify activity was logged
+ assert len(mock_bridge.events) == 1
+ event = mock_bridge.events[0]
+ assert event[0] == "mcp_activity"
+ assert event[1] == "protocol"
+ assert "SimpleMockMessage" in event[2] # Type name
+
+ @pytest.mark.asyncio
+ async def test_sampling_callback_success(self, mock_bridge):
+ """Test sampling callback success case"""
+ callback = create_sampling_callback(mock_bridge)
+
+ # Create mock context and params
+ mock_context = AsyncMock(spec=RequestContext)
+ mock_params = CreateMessageRequestParams(
+ messages=[], # Empty messages array for test
+ maxTokens=100
+ )
+
+ result = await callback(mock_context, mock_params)
+
+ # Verify result is CreateMessageResult
+ assert isinstance(result, CreateMessageResult)
+ assert result.role == "assistant"
+ assert result.model == "autogen-studio-default"
+ assert isinstance(result.content, TextContent)
+ assert "AutoGen Studio Default Sampling Response" in result.content.text
+
+ # Verify activities were logged
+ assert len(mock_bridge.events) == 2
+ # First event: sampling request
+ assert mock_bridge.events[0][1] == "sampling"
+ assert "Tool requested AI sampling" in mock_bridge.events[0][2]
+ # Second event: sampling response
+ assert mock_bridge.events[1][1] == "sampling"
+ assert "Provided default sampling response" in mock_bridge.events[1][2]
+
+ @pytest.mark.asyncio
+ async def test_sampling_callback_exception(self, mock_bridge):
+ """Test sampling callback with exception"""
+ callback = create_sampling_callback(mock_bridge)
+
+ # Create mock context that raises exception
+ mock_context = AsyncMock(spec=RequestContext)
+
+ # Create params that will cause an exception when accessing
+ mock_params = MagicMock()
+ mock_params.messages = None # This should cause an error
+
+ # Mock the model_dump to raise exception
+ mock_params.model_dump.side_effect = Exception("Test sampling error")
+
+ result = await callback(mock_context, mock_params)
+
+ # Verify result is ErrorData
+ assert isinstance(result, ErrorData)
+ assert result.code == -32603
+ assert "Sampling failed" in result.message
+
+ # Verify error was logged
+ error_events = [e for e in mock_bridge.events if e[1] == "error"]
+ assert len(error_events) == 1
+ assert "Sampling callback error" in error_events[0][2]
+
+ @pytest.mark.asyncio
+ async def test_elicitation_callback_success(self, mock_bridge):
+ """Test elicitation callback success case"""
+ callback, pending_dict = create_elicitation_callback(mock_bridge)
+
+ # Verify that pending_dict is the same as bridge's pending_elicitations
+ assert pending_dict is mock_bridge.pending_elicitations
+
+ # Create mock context and params
+ mock_context = AsyncMock(spec=RequestContext)
+ mock_params = ElicitRequestParams(
+ message="Please provide your name",
+ requestedSchema={"type": "string"}
+ )
+
+ # Create a task to simulate user response
+ async def simulate_user_response():
+ await asyncio.sleep(0.1) # Let elicitation setup
+
+ # Find the request ID from events
+ elicit_events = [e for e in mock_bridge.events if e[0] == "elicitation_request"]
+ assert len(elicit_events) == 1
+ request_id = elicit_events[0][1]
+
+ # Simulate user accepting
+ if request_id in mock_bridge.pending_elicitations:
+ future = mock_bridge.pending_elicitations[request_id]
+ result = ElicitResult(action="accept", content={"name": "John Doe"})
+ future.set_result(result)
+
+ # Run both the callback and the response simulation
+ callback_task = asyncio.create_task(callback(mock_context, mock_params))
+ response_task = asyncio.create_task(simulate_user_response())
+
+ result, _ = await asyncio.gather(callback_task, response_task)
+
+ # Verify result
+ assert isinstance(result, ElicitResult)
+ assert result.action == "accept"
+ assert result.content == {"name": "John Doe"}
+
+ # Verify events were logged
+ activity_events = [e for e in mock_bridge.events if e[0] == "mcp_activity"]
+ elicit_events = [e for e in mock_bridge.events if e[0] == "elicitation_request"]
+
+ assert len(elicit_events) == 1
+ assert len(activity_events) >= 2 # Request and response activities
+
+ @pytest.mark.asyncio
+ async def test_elicitation_callback_timeout(self, mock_bridge):
+ """Test elicitation callback timeout"""
+ callback, _ = create_elicitation_callback(mock_bridge)
+
+ # Create mock context and params
+ mock_context = AsyncMock(spec=RequestContext)
+ mock_params = ElicitRequestParams(
+ message="Please provide input",
+ requestedSchema={"type": "string"}
+ )
+
+ # Mock asyncio.wait_for to raise TimeoutError
+ with patch('asyncio.wait_for', side_effect=asyncio.TimeoutError):
+ result = await callback(mock_context, mock_params)
+
+ # Verify result is ErrorData
+ assert isinstance(result, ErrorData)
+ assert result.code == -32603
+ assert "60 seconds" in result.message
+
+ # Verify timeout was logged
+ error_events = [e for e in mock_bridge.events if e[1] == "error"]
+ assert len(error_events) == 1
+ assert "Elicitation timeout" in error_events[0][2]
+
+ @pytest.mark.asyncio
+ async def test_elicitation_callback_exception(self, mock_bridge):
+ """Test elicitation callback with exception"""
+ callback, _ = create_elicitation_callback(mock_bridge)
+
+ # Create mock context and params that will cause exception
+ mock_context = AsyncMock(spec=RequestContext)
+ mock_params = MagicMock()
+ mock_params.message = "Test message"
+ mock_params.requestedSchema = None
+
+ # Mock uuid.uuid4 to raise exception
+ with patch('uuid.uuid4', side_effect=Exception("UUID generation failed")):
+ result = await callback(mock_context, mock_params)
+
+ # Verify result is ErrorData
+ assert isinstance(result, ErrorData)
+ assert result.code == -32603
+ assert "Elicitation failed" in result.message
+
+ # Verify error was logged
+ error_events = [e for e in mock_bridge.events if e[1] == "error"]
+ assert len(error_events) == 1
+ assert "Elicitation callback error" in error_events[0][2]
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])
diff --git a/python/packages/autogen-studio/tests/mcp/test_mcp_client.py b/python/packages/autogen-studio/tests/mcp/test_mcp_client.py
new file mode 100644
index 000000000..289b81500
--- /dev/null
+++ b/python/packages/autogen-studio/tests/mcp/test_mcp_client.py
@@ -0,0 +1,267 @@
+#!/usr/bin/env python3
+"""Test the MCP client implementation"""
+
+import asyncio
+import pytest
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+from datetime import datetime, timezone
+
+from mcp.types import (
+ ListToolsResult,
+ Tool,
+ CallToolResult,
+ TextContent,
+ ListResourcesResult,
+ Resource,
+ ReadResourceResult,
+ TextResourceContents,
+ ListPromptsResult,
+ Prompt,
+ GetPromptResult,
+ PromptMessage,
+ InitializeResult,
+ ServerCapabilities,
+ Implementation
+)
+
+from autogenstudio.mcp.client import MCPClient, MCPEventHandler
+from autogenstudio.mcp.utils import McpOperationError
+
+
+class MockEventHandler(MCPEventHandler):
+ """Mock event handler for testing"""
+
+ def __init__(self):
+ self.events = []
+
+ async def on_initialized(self, session_id: str, capabilities: Any) -> None:
+ self.events.append(("initialized", session_id, capabilities))
+
+ async def on_operation_result(self, operation: str, data: dict) -> None:
+ self.events.append(("operation_result", operation, data))
+
+ async def on_operation_error(self, operation: str, error: str) -> None:
+ self.events.append(("operation_error", operation, error))
+
+ async def on_mcp_activity(self, activity_type: str, message: str, details: dict) -> None:
+ self.events.append(("mcp_activity", activity_type, message, details))
+
+ async def on_elicitation_request(self, request_id: str, message: str, requested_schema: Any) -> None:
+ self.events.append(("elicitation_request", request_id, message, requested_schema))
+
+
+class TestMCPClient:
+ """Test the MCPClient class"""
+
+ @pytest.fixture
+ def mock_session(self):
+ """Create a mock MCP session"""
+ session = AsyncMock()
+
+ # Mock initialization
+ session.initialize.return_value = InitializeResult(
+ protocolVersion="2024-11-05",
+ capabilities=ServerCapabilities(),
+ serverInfo=Implementation(name="test-server", version="1.0.0")
+ )
+
+ # Mock tools
+ session.list_tools.return_value = ListToolsResult(
+ tools=[
+ Tool(
+ name="test_tool",
+ description="A test tool",
+ inputSchema={
+ "type": "object",
+ "properties": {"message": {"type": "string"}},
+ "required": ["message"]
+ }
+ )
+ ]
+ )
+
+ # Mock tool call
+ session.call_tool.return_value = CallToolResult(
+ content=[TextContent(type="text", text="Tool executed successfully")],
+ isError=False
+ )
+
+ # Mock resources
+ from pydantic import HttpUrl
+ test_uri = HttpUrl("https://example.com/test.txt")
+ session.list_resources.return_value = ListResourcesResult(
+ resources=[
+ Resource(
+ uri=test_uri,
+ name="test.txt",
+ description="A test resource",
+ mimeType="text/plain"
+ )
+ ]
+ )
+
+ session.read_resource.return_value = ReadResourceResult(
+ contents=[TextResourceContents(
+ uri=test_uri,
+ text="This is test content",
+ mimeType="text/plain"
+ )]
+ )
+
+ # Mock prompts
+ session.list_prompts.return_value = ListPromptsResult(
+ prompts=[
+ Prompt(
+ name="test_prompt",
+ description="A test prompt"
+ )
+ ]
+ )
+
+ session.get_prompt.return_value = GetPromptResult(
+ description="Test prompt result",
+ messages=[
+ PromptMessage(
+ role="user",
+ content=TextContent(type="text", text="Test prompt content")
+ )
+ ]
+ )
+
+ return session
+
+ @pytest.fixture
+ def mock_event_handler(self):
+ """Create a mock event handler"""
+ return MockEventHandler()
+
+ @pytest.mark.asyncio
+ async def test_client_initialization(self, mock_session, mock_event_handler):
+ """Test MCPClient initialization"""
+ client = MCPClient(mock_session, "test-session", mock_event_handler)
+
+ assert client.session == mock_session
+ assert client.session_id == "test-session"
+ assert client.event_handler == mock_event_handler
+ assert not client._initialized
+ assert client._capabilities is None
+
+ @pytest.mark.asyncio
+ async def test_client_initialize(self, mock_session, mock_event_handler):
+ """Test MCPClient.initialize()"""
+ client = MCPClient(mock_session, "test-session", mock_event_handler)
+
+ await client.initialize()
+
+ # Verify session.initialize was called
+ mock_session.initialize.assert_called_once()
+
+ # Verify client state
+ assert client._initialized
+ assert client.capabilities is not None
+
+ # Verify event handler was called
+ events = [e for e in mock_event_handler.events if e[0] == "initialized"]
+ assert len(events) == 1
+ assert events[0][1] == "test-session"
+
+ @pytest.mark.asyncio
+ async def test_list_tools_operation(self, mock_session, mock_event_handler):
+ """Test list_tools operation"""
+ client = MCPClient(mock_session, "test-session", mock_event_handler)
+ await client.initialize()
+
+ # Test list_tools operation
+ operation = {"operation": "list_tools"}
+ await client.handle_operation(operation)
+
+ # Verify session method was called
+ mock_session.list_tools.assert_called_once()
+
+ # Verify result event was fired
+ result_events = [e for e in mock_event_handler.events if e[0] == "operation_result"]
+ assert len(result_events) == 1
+ assert result_events[0][1] == "list_tools"
+ assert "tools" in result_events[0][2]
+
+ @pytest.mark.asyncio
+ async def test_call_tool_operation(self, mock_session, mock_event_handler):
+ """Test call_tool operation"""
+ client = MCPClient(mock_session, "test-session", mock_event_handler)
+ await client.initialize()
+
+ # Test call_tool operation
+ operation = {
+ "operation": "call_tool",
+ "tool_name": "test_tool",
+ "arguments": {"message": "test"}
+ }
+ await client.handle_operation(operation)
+
+ # Verify session method was called
+ mock_session.call_tool.assert_called_once_with("test_tool", {"message": "test"})
+
+ # Verify result event was fired
+ result_events = [e for e in mock_event_handler.events if e[0] == "operation_result"]
+ assert len(result_events) == 1
+ assert result_events[0][1] == "call_tool"
+ assert result_events[0][2]["tool_name"] == "test_tool"
+
+ @pytest.mark.asyncio
+ async def test_call_tool_missing_name(self, mock_session, mock_event_handler):
+ """Test call_tool operation with missing tool name"""
+ client = MCPClient(mock_session, "test-session", mock_event_handler)
+ await client.initialize()
+
+ # Test call_tool operation without tool_name
+ operation = {
+ "operation": "call_tool",
+ "arguments": {"message": "test"}
+ }
+ await client.handle_operation(operation)
+
+ # Verify error event was fired
+ error_events = [e for e in mock_event_handler.events if e[0] == "operation_error"]
+ assert len(error_events) == 1
+ assert error_events[0][1] == "call_tool"
+ assert "Tool name is required" in error_events[0][2]
+
+ @pytest.mark.asyncio
+ async def test_unknown_operation(self, mock_session, mock_event_handler):
+ """Test unknown operation handling"""
+ client = MCPClient(mock_session, "test-session", mock_event_handler)
+ await client.initialize()
+
+ # Test unknown operation
+ operation = {"operation": "unknown_op"}
+ await client.handle_operation(operation)
+
+ # Verify error event was fired
+ error_events = [e for e in mock_event_handler.events if e[0] == "operation_error"]
+ assert len(error_events) == 1
+ assert error_events[0][1] == "unknown_op"
+ assert "Unknown operation" in error_events[0][2]
+
+ @pytest.mark.asyncio
+ async def test_operation_exception_handling(self, mock_session, mock_event_handler):
+ """Test operation exception handling"""
+ client = MCPClient(mock_session, "test-session", mock_event_handler)
+ await client.initialize()
+
+ # Mock session to raise exception
+ mock_session.list_tools.side_effect = Exception("Test error")
+
+ # Test list_tools operation
+ operation = {"operation": "list_tools"}
+ await client.handle_operation(operation)
+
+ # Verify error event was fired
+ error_events = [e for e in mock_event_handler.events if e[0] == "operation_error"]
+ assert len(error_events) == 1
+ assert error_events[0][1] == "list_tools"
+ assert "Test error" in error_events[0][2]
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])
diff --git a/python/packages/autogen-studio/tests/mcp/test_mcp_integration.py b/python/packages/autogen-studio/tests/mcp/test_mcp_integration.py
new file mode 100644
index 000000000..7dd237156
--- /dev/null
+++ b/python/packages/autogen-studio/tests/mcp/test_mcp_integration.py
@@ -0,0 +1,252 @@
+#!/usr/bin/env python3
+"""Test the integration of all MCP components"""
+
+import asyncio
+import json
+import base64
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+from datetime import datetime, timezone
+
+from fastapi import WebSocket
+from autogen_ext.tools.mcp._config import StdioServerParams
+
+from autogenstudio.mcp.client import MCPClient
+from autogenstudio.mcp.wsbridge import MCPWebSocketBridge
+from autogenstudio.mcp.callbacks import create_message_handler, create_sampling_callback, create_elicitation_callback
+from autogenstudio.mcp.utils import extract_real_error, serialize_for_json, is_websocket_disconnect, McpOperationError
+
+
+class TestMCPIntegration:
+ """Test integration of MCP components"""
+
+ @pytest.mark.asyncio
+ async def test_end_to_end_operation_flow(self):
+ """Test complete operation flow from WebSocket to MCP client"""
+ # Create mock WebSocket
+ mock_websocket = MagicMock(spec=WebSocket)
+ from fastapi.websockets import WebSocketState
+ mock_websocket.client_state = WebSocketState.CONNECTED
+ mock_websocket.send_json = AsyncMock()
+
+ # Create bridge
+ bridge = MCPWebSocketBridge(mock_websocket, "test-session")
+
+ # Create mock MCP session
+ mock_session = AsyncMock()
+ mock_session.initialize.return_value = AsyncMock()
+ mock_session.initialize.return_value.capabilities = AsyncMock()
+ mock_session.list_tools.return_value = AsyncMock()
+ mock_session.list_tools.return_value.tools = []
+
+ # Create and set MCP client
+ client = MCPClient(mock_session, "test-session", bridge)
+ bridge.set_mcp_client(client)
+
+ # Initialize client
+ await client.initialize()
+
+ # Test operation flow
+ operation_message = {
+ "type": "operation",
+ "operation": "list_tools"
+ }
+
+ # Handle the operation (should run in background task)
+ await bridge.handle_websocket_message(operation_message)
+
+ # Give background task time to complete
+ await asyncio.sleep(0.1)
+
+ # Verify session method was called
+ mock_session.list_tools.assert_called_once()
+
+ # Verify WebSocket messages were sent
+ assert mock_websocket.send_json.call_count >= 2 # initialized + operation_result
+
+ @pytest.mark.asyncio
+ async def test_elicitation_integration(self):
+ """Test elicitation flow integration"""
+ # Create mock WebSocket
+ mock_websocket = MagicMock(spec=WebSocket)
+ mock_websocket.client_state = "CONNECTED"
+ mock_websocket.send_json = AsyncMock()
+
+ # Create bridge
+ bridge = MCPWebSocketBridge(mock_websocket, "test-session")
+
+ # Create elicitation callback
+ elicitation_callback, pending_dict = create_elicitation_callback(bridge)
+
+ # Verify that pending_dict is the bridge's pending_elicitations
+ assert pending_dict is bridge.pending_elicitations
+
+ # Test that bridge can handle elicitation responses
+ assert hasattr(bridge, 'pending_elicitations')
+ assert isinstance(bridge.pending_elicitations, dict)
+
+
+class TestMCPUtils:
+ """Test MCP utility functions"""
+
+ def test_extract_real_error_simple(self):
+ """Test extract_real_error with simple exception"""
+ error = ValueError("Test error message")
+ result = extract_real_error(error)
+ assert "ValueError: Test error message" in result
+
+ def test_extract_real_error_chained(self):
+ """Test extract_real_error with chained exceptions"""
+ try:
+ try:
+ raise ValueError("Original error")
+ except ValueError as e:
+ raise RuntimeError("Wrapper error") from e
+ except RuntimeError as e:
+ result = extract_real_error(e)
+ assert "RuntimeError: Wrapper error" in result
+ assert "ValueError: Original error" in result
+
+ def test_extract_real_error_with_context(self):
+ """Test extract_real_error with context exceptions"""
+ try:
+ try:
+ raise ValueError("Context error")
+ except ValueError:
+ raise RuntimeError("Main error")
+ except RuntimeError as e:
+ result = extract_real_error(e)
+ assert "RuntimeError: Main error" in result
+ assert "ValueError: Context error" in result
+
+ def test_serialize_for_json_simple_types(self):
+ """Test serialize_for_json with simple types"""
+ assert serialize_for_json("string") == "string"
+ assert serialize_for_json(42) == 42
+ assert serialize_for_json(True) is True
+ assert serialize_for_json(None) is None
+
+ def test_serialize_for_json_dict(self):
+ """Test serialize_for_json with dictionary"""
+ data = {
+ "string": "value",
+ "number": 42,
+ "bool": True,
+ "nested": {"inner": "value"}
+ }
+ result = serialize_for_json(data)
+ assert result == {
+ "string": "value",
+ "number": 42,
+ "bool": True,
+ "nested": {"inner": "value"}
+ }
+
+ def test_serialize_for_json_list(self):
+ """Test serialize_for_json with list"""
+ data = ["string", 42, True, {"nested": "value"}]
+ result = serialize_for_json(data)
+ assert result == ["string", 42, True, {"nested": "value"}]
+
+ def test_serialize_for_json_with_model_dump(self):
+ """Test serialize_for_json with object that has model_dump"""
+ mock_obj = MagicMock()
+ mock_obj.model_dump.return_value = {"key": "value"}
+
+ result = serialize_for_json(mock_obj)
+ assert result == {"key": "value"}
+ mock_obj.model_dump.assert_called_once()
+
+ def test_serialize_for_json_with_anyurl(self):
+ """Test serialize_for_json with AnyUrl"""
+ from pydantic import HttpUrl
+ url = HttpUrl("https://example.com/test")
+ result = serialize_for_json(url)
+ assert result == "https://example.com/test"
+
+ def test_is_websocket_disconnect_with_websocket_disconnect(self):
+ """Test is_websocket_disconnect with WebSocketDisconnect"""
+ from fastapi import WebSocketDisconnect
+ error = WebSocketDisconnect(code=1000, reason="Normal closure")
+ assert is_websocket_disconnect(error) is True
+
+ def test_is_websocket_disconnect_with_regular_exception(self):
+ """Test is_websocket_disconnect with regular exception"""
+ error = ValueError("Regular error")
+ assert is_websocket_disconnect(error) is False
+
+ def test_is_websocket_disconnect_with_nested_exception(self):
+ """Test is_websocket_disconnect with nested WebSocketDisconnect"""
+ from fastapi import WebSocketDisconnect
+
+ # Create a nested exception structure
+ try:
+ try:
+ raise WebSocketDisconnect(code=1000, reason="Normal closure")
+ except WebSocketDisconnect as e:
+ raise RuntimeError("Wrapper") from e
+ except RuntimeError as e:
+ assert is_websocket_disconnect(e) is True
+
+ def test_is_websocket_disconnect_with_no_status_rcvd(self):
+ """Test is_websocket_disconnect with NO_STATUS_RCVD message"""
+ error = Exception("Connection closed with NO_STATUS_RCVD")
+ assert is_websocket_disconnect(error) is True
+
+ def test_is_websocket_disconnect_with_websocket_in_name(self):
+ """Test is_websocket_disconnect with WebSocket in exception name"""
+ class CustomWebSocketDisconnectError(Exception):
+ pass
+
+ error = CustomWebSocketDisconnectError("Custom disconnect")
+ assert is_websocket_disconnect(error) is True
+
+ def test_mcp_operation_error(self):
+ """Test McpOperationError exception"""
+ error = McpOperationError("Test operation failed")
+ assert str(error) == "Test operation failed"
+ assert isinstance(error, Exception)
+
+
+class TestMCPRouteIntegration:
+ """Test integration with route components"""
+
+ def test_server_params_serialization(self):
+ """Test that server params can be serialized/deserialized correctly"""
+ server_params = StdioServerParams(
+ command="test-command",
+ args=["--arg1", "value1"],
+ env={"ENV_VAR": "value"}
+ )
+
+ # Test serialization
+ serialized = serialize_for_json(server_params.model_dump())
+ assert isinstance(serialized, dict)
+ assert serialized["command"] == "test-command"
+ assert serialized["args"] == ["--arg1", "value1"]
+ assert serialized["env"] == {"ENV_VAR": "value"}
+
+ def test_websocket_url_encoding(self):
+ """Test WebSocket URL parameter encoding"""
+ server_params = StdioServerParams(
+ command="test-command",
+ args=["--test"],
+ env={}
+ )
+
+ # Simulate the encoding process from the route
+ server_params_json = json.dumps(serialize_for_json(server_params.model_dump()))
+ server_params_encoded = base64.b64encode(server_params_json.encode("utf-8")).decode("utf-8")
+
+ # Test decoding
+ decoded_params = base64.b64decode(server_params_encoded).decode("utf-8")
+ server_params_dict = json.loads(decoded_params)
+
+ assert server_params_dict["command"] == "test-command"
+ assert server_params_dict["args"] == ["--test"]
+ assert server_params_dict["env"] == {}
+ assert server_params_dict["type"] == "StdioServerParams"
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])
diff --git a/python/packages/autogen-studio/tests/mcp/test_mcp_websocket.py b/python/packages/autogen-studio/tests/mcp/test_mcp_websocket.py
new file mode 100644
index 000000000..87d973ce9
--- /dev/null
+++ b/python/packages/autogen-studio/tests/mcp/test_mcp_websocket.py
@@ -0,0 +1,312 @@
+"""
+Updated tests for MCP WebSocket functionality using the new refactored architecture.
+These tests replace the failing legacy tests in test_mcp_websocket.py.
+"""
+
+import json
+import base64
+from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
+from fastapi import WebSocket
+
+# Import the new architecture components
+from autogenstudio.mcp.client import MCPClient
+from autogenstudio.mcp.wsbridge import MCPWebSocketBridge
+
+# Import MCP types for mocking
+from mcp.types import (
+ Tool, Resource, Prompt, PromptArgument,
+ ListToolsResult, CallToolResult, ListResourcesResult,
+ ReadResourceResult, ListPromptsResult, GetPromptResult,
+ TextContent, TextResourceContents, PromptMessage,
+ ServerCapabilities, ToolsCapability, ResourcesCapability, PromptsCapability
+)
+from autogen_ext.tools.mcp._config import StdioServerParams
+
+
+class TestMCPWebSocketUpdated:
+ """Updated tests for MCP WebSocket functionality"""
+
+ @pytest.fixture
+ def mock_server_params(self):
+ """Create mock server parameters"""
+ return StdioServerParams(
+ command="node",
+ args=["server.js"],
+ env={"NODE_ENV": "test"}
+ )
+
+ @pytest.fixture
+ def mock_client_session(self):
+ """Create a mock MCP client session with all necessary methods"""
+ mock_session = AsyncMock()
+
+ # Mock initialization result
+ mock_init_result = MagicMock()
+ mock_init_result.capabilities = ServerCapabilities(
+ tools=ToolsCapability(listChanged=False),
+ resources=ResourcesCapability(subscribe=False, listChanged=False),
+ prompts=PromptsCapability(listChanged=False)
+ )
+ mock_session.initialize.return_value = mock_init_result
+
+ # Mock tools
+ mock_tools = [
+ Tool(
+ name="test_tool",
+ description="A test tool",
+ inputSchema={
+ "type": "object",
+ "properties": {"message": {"type": "string"}},
+ "required": ["message"]
+ }
+ )
+ ]
+ mock_session.list_tools.return_value = ListToolsResult(tools=mock_tools)
+
+ # Mock call tool result
+ mock_call_result = CallToolResult(
+ content=[TextContent(type="text", text="Tool executed successfully")],
+ isError=False
+ )
+ mock_session.call_tool.return_value = mock_call_result
+
+ # Mock resources
+ from pydantic import HttpUrl
+ test_uri = HttpUrl("https://example.com/test.txt")
+ mock_resources = [
+ Resource(
+ uri=test_uri,
+ name="test.txt",
+ description="A test resource",
+ mimeType="text/plain"
+ )
+ ]
+ mock_session.list_resources.return_value = ListResourcesResult(resources=mock_resources)
+
+ # Mock resource content
+ mock_resource_content = ReadResourceResult(
+ contents=[TextResourceContents(
+ uri=test_uri,
+ text="This is test content",
+ mimeType="text/plain"
+ )]
+ )
+ mock_session.read_resource.return_value = mock_resource_content
+
+ # Mock prompts
+ mock_prompts = [
+ Prompt(
+ name="test_prompt",
+ description="A test prompt",
+ arguments=[
+ PromptArgument(
+ name="input",
+ description="Input text",
+ required=True
+ )
+ ]
+ )
+ ]
+ mock_session.list_prompts.return_value = ListPromptsResult(prompts=mock_prompts)
+
+ # Mock prompt result
+ mock_prompt_result = GetPromptResult(
+ description="Test prompt result",
+ messages=[
+ PromptMessage(
+ role="user",
+ content=TextContent(type="text", text="Test message")
+ )
+ ]
+ )
+ mock_session.get_prompt.return_value = mock_prompt_result
+
+ return mock_session
+
+ @pytest.fixture
+ def mock_websocket(self):
+ """Create a mock WebSocket"""
+ mock_ws = AsyncMock(spec=WebSocket)
+ from fastapi.websockets import WebSocketState
+ mock_ws.client_state = WebSocketState.CONNECTED
+ return mock_ws
+
+ @pytest.mark.asyncio
+ async def test_websocket_bridge_send_message(self, mock_websocket):
+ """Test WebSocket message sending via MCPWebSocketBridge"""
+ bridge = MCPWebSocketBridge(mock_websocket, "test_session")
+ test_message = {"type": "test", "data": "hello"}
+
+ await bridge.send_message(test_message)
+ mock_websocket.send_json.assert_called_once_with(test_message)
+
+ @pytest.mark.asyncio
+ async def test_mcp_client_list_tools_operation(self, mock_websocket, mock_client_session):
+ """Test handling list_tools operation via MCPClient"""
+ bridge = MCPWebSocketBridge(mock_websocket, "test_session")
+ client = MCPClient(mock_client_session, "test_session", bridge)
+
+ operation = {"operation": "list_tools"}
+
+ await client.handle_operation(operation)
+
+ # Verify the session method was called
+ mock_client_session.list_tools.assert_called_once()
+
+ # Verify WebSocket response was sent
+ mock_websocket.send_json.assert_called_once()
+ sent_message = mock_websocket.send_json.call_args[0][0]
+ assert sent_message["type"] == "operation_result"
+ assert sent_message["operation"] == "list_tools"
+ assert "data" in sent_message
+ assert "tools" in sent_message["data"]
+
+ @pytest.mark.asyncio
+ async def test_mcp_client_call_tool_operation(self, mock_websocket, mock_client_session):
+ """Test handling call_tool operation via MCPClient"""
+ bridge = MCPWebSocketBridge(mock_websocket, "test_session")
+ client = MCPClient(mock_client_session, "test_session", bridge)
+
+ operation = {
+ "operation": "call_tool",
+ "tool_name": "test_tool",
+ "arguments": {"message": "hello"}
+ }
+
+ await client.handle_operation(operation)
+
+ # Verify the session method was called with correct arguments
+ mock_client_session.call_tool.assert_called_once_with("test_tool", {"message": "hello"})
+
+ # Verify WebSocket response was sent
+ mock_websocket.send_json.assert_called_once()
+ sent_message = mock_websocket.send_json.call_args[0][0]
+ assert sent_message["type"] == "operation_result"
+ assert sent_message["operation"] == "call_tool"
+
+ @pytest.mark.asyncio
+ async def test_mcp_client_list_resources_operation(self, mock_websocket, mock_client_session):
+ """Test handling list_resources operation via MCPClient"""
+ bridge = MCPWebSocketBridge(mock_websocket, "test_session")
+ client = MCPClient(mock_client_session, "test_session", bridge)
+
+ operation = {"operation": "list_resources"}
+
+ await client.handle_operation(operation)
+
+ mock_client_session.list_resources.assert_called_once()
+ mock_websocket.send_json.assert_called_once()
+ sent_message = mock_websocket.send_json.call_args[0][0]
+ assert sent_message["type"] == "operation_result"
+ assert sent_message["operation"] == "list_resources"
+
+ @pytest.mark.asyncio
+ async def test_mcp_client_read_resource_operation(self, mock_websocket, mock_client_session):
+ """Test handling read_resource operation via MCPClient"""
+ bridge = MCPWebSocketBridge(mock_websocket, "test_session")
+ client = MCPClient(mock_client_session, "test_session", bridge)
+
+ operation = {
+ "operation": "read_resource",
+ "uri": "https://example.com/test.txt"
+ }
+
+ await client.handle_operation(operation)
+
+ mock_client_session.read_resource.assert_called_once_with("https://example.com/test.txt")
+ mock_websocket.send_json.assert_called_once()
+ sent_message = mock_websocket.send_json.call_args[0][0]
+ assert sent_message["type"] == "operation_result"
+ assert sent_message["operation"] == "read_resource"
+
+ @pytest.mark.asyncio
+ async def test_mcp_client_error_handling(self, mock_websocket, mock_client_session):
+ """Test error handling in MCP operations via MCPClient"""
+ bridge = MCPWebSocketBridge(mock_websocket, "test_session")
+ client = MCPClient(mock_client_session, "test_session", bridge)
+
+ # Make the session raise an exception
+ mock_client_session.list_tools.side_effect = Exception("Test error")
+
+ operation = {"operation": "list_tools"}
+
+ await client.handle_operation(operation)
+
+ # Verify operation error response was sent
+ mock_websocket.send_json.assert_called_once()
+ sent_message = mock_websocket.send_json.call_args[0][0]
+ assert sent_message["type"] == "operation_error"
+ assert sent_message["operation"] == "list_tools"
+ assert "Test error" in sent_message["error"]
+
+ def test_websocket_connection_url_generation(self, mock_server_params):
+ """Test WebSocket connection URL generation (preserved from original tests)"""
+ session_id = "test-session-123"
+
+ # Test the URL generation logic
+ server_params_json = json.dumps(mock_server_params.model_dump())
+ encoded_params = base64.b64encode(server_params_json.encode()).decode()
+
+ expected_url = f"ws://localhost:8000/ws/mcp?session_id={session_id}&server_params={encoded_params}"
+
+ # This is a functional test - just verify the encoding/decoding works
+ decoded_params = base64.b64decode(encoded_params.encode()).decode()
+ decoded_obj = json.loads(decoded_params)
+
+ assert decoded_obj["command"] == "node"
+ assert decoded_obj["args"] == ["server.js"]
+ assert decoded_obj["env"]["NODE_ENV"] == "test"
+
+ def test_active_sessions_structure(self):
+ """Test active sessions data structure (preserved from original tests)"""
+ from autogenstudio.web.routes.mcp import active_sessions
+
+ # Test that active_sessions is a dictionary
+ assert isinstance(active_sessions, dict)
+
+ # Test adding a session
+ session_id = "test-session"
+ session_data = {
+ "session_id": session_id,
+ "server_params": {"command": "node", "args": ["server.js"]},
+ "last_activity": "2023-01-01T00:00:00Z",
+ "status": "active"
+ }
+
+ active_sessions[session_id] = session_data
+ assert session_id in active_sessions
+ assert active_sessions[session_id] == session_data
+
+ # Clean up
+ del active_sessions[session_id]
+
+
+class TestMCPRouteIntegrationUpdated:
+ """Updated integration tests for MCP routes"""
+
+ def test_router_exists(self):
+ """Test that the MCP router exists and is properly configured"""
+ from autogenstudio.web.routes.mcp import router
+ from fastapi import APIRouter
+
+ assert isinstance(router, APIRouter)
+
+ def test_create_websocket_connection_request_model(self):
+ """Test the request model for creating WebSocket connections"""
+ from autogenstudio.web.routes.mcp import CreateWebSocketConnectionRequest
+ from autogen_ext.tools.mcp._config import StdioServerParams
+
+ # Test creating a request with valid server params
+ server_params = StdioServerParams(
+ command="node",
+ args=["server.js"],
+ env={"NODE_ENV": "test"}
+ )
+
+ request = CreateWebSocketConnectionRequest(server_params=server_params)
+ assert request.server_params == server_params
+ # Type-check that server_params is StdioServerParams
+ assert isinstance(request.server_params, StdioServerParams)
+ assert request.server_params.command == "node"
+ assert request.server_params.args == ["server.js"]
diff --git a/python/packages/autogen-studio/tests/mcp/test_mcp_wsbridge.py b/python/packages/autogen-studio/tests/mcp/test_mcp_wsbridge.py
new file mode 100644
index 000000000..6a06d9015
--- /dev/null
+++ b/python/packages/autogen-studio/tests/mcp/test_mcp_wsbridge.py
@@ -0,0 +1,350 @@
+#!/usr/bin/env python3
+"""Test the MCPWebSocketBridge implementation"""
+
+import asyncio
+import json
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+from datetime import datetime, timezone
+
+from fastapi import WebSocket
+from mcp.types import ElicitResult, ErrorData
+
+from autogenstudio.mcp.wsbridge import MCPWebSocketBridge
+from autogenstudio.mcp.client import MCPClient
+
+
+class MockWebSocket:
+ """Mock WebSocket for testing"""
+
+ def __init__(self):
+ self.messages_sent = []
+ self.messages_to_receive = []
+ self.receive_index = 0
+ # Use the actual enum value
+ from fastapi.websockets import WebSocketState
+ self.client_state = WebSocketState.CONNECTED
+
+ async def send_json(self, data):
+ self.messages_sent.append(data)
+
+ async def receive_text(self):
+ if self.receive_index < len(self.messages_to_receive):
+ message = self.messages_to_receive[self.receive_index]
+ self.receive_index += 1
+ return message
+ else:
+ # Simulate WebSocket close
+ raise Exception("WebSocket closed")
+
+ def add_message(self, message):
+ self.messages_to_receive.append(json.dumps(message) if isinstance(message, dict) else message)
+
+
+class TestMCPWebSocketBridge:
+ """Test the MCPWebSocketBridge class"""
+
+ @pytest.fixture
+ def mock_websocket(self):
+ """Create a mock WebSocket"""
+ return MockWebSocket()
+
+ @pytest.fixture
+ def bridge(self, mock_websocket):
+ """Create a MCPWebSocketBridge instance"""
+ return MCPWebSocketBridge(mock_websocket, "test-session")
+
+ @pytest.mark.asyncio
+ async def test_bridge_initialization(self, bridge, mock_websocket):
+ """Test bridge initialization"""
+ assert bridge.websocket == mock_websocket
+ assert bridge.session_id == "test-session"
+ assert bridge.mcp_client is None
+ assert bridge.pending_elicitations == {}
+ assert bridge._running is True
+
+ @pytest.mark.asyncio
+ async def test_send_message(self, bridge, mock_websocket):
+ """Test message sending through WebSocket"""
+ test_message = {
+ "type": "test",
+ "data": "test_data",
+ "timestamp": datetime.now(timezone.utc).isoformat()
+ }
+
+ await bridge.send_message(test_message)
+
+ assert len(mock_websocket.messages_sent) == 1
+ assert mock_websocket.messages_sent[0]["type"] == "test"
+ assert mock_websocket.messages_sent[0]["data"] == "test_data"
+
+ @pytest.mark.asyncio
+ async def test_on_initialized_event(self, bridge, mock_websocket):
+ """Test on_initialized event handler"""
+ capabilities = {"tools": True, "resources": True}
+
+ await bridge.on_initialized("test-session", capabilities)
+
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "initialized"
+ assert message["session_id"] == "test-session"
+ assert message["capabilities"] == capabilities
+
+ @pytest.mark.asyncio
+ async def test_on_operation_result_event(self, bridge, mock_websocket):
+ """Test on_operation_result event handler"""
+ operation = "list_tools"
+ data = {"tools": [{"name": "test_tool"}]}
+
+ await bridge.on_operation_result(operation, data)
+
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "operation_result"
+ assert message["operation"] == operation
+ assert message["data"] == data
+
+ @pytest.mark.asyncio
+ async def test_on_operation_error_event(self, bridge, mock_websocket):
+ """Test on_operation_error event handler"""
+ operation = "call_tool"
+ error = "Tool not found"
+
+ await bridge.on_operation_error(operation, error)
+
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "operation_error"
+ assert message["operation"] == operation
+ assert message["error"] == error
+
+ @pytest.mark.asyncio
+ async def test_on_elicitation_request_event(self, bridge, mock_websocket):
+ """Test on_elicitation_request event handler"""
+ request_id = "test-request-123"
+ message_text = "Please provide input"
+ schema = {"type": "string"}
+
+ await bridge.on_elicitation_request(request_id, message_text, schema)
+
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "elicitation_request"
+ assert message["request_id"] == request_id
+ assert message["message"] == message_text
+ assert message["requestedSchema"] == schema
+
+ @pytest.mark.asyncio
+ async def test_set_mcp_client(self, bridge):
+ """Test setting MCP client"""
+ mock_client = MagicMock(spec=MCPClient)
+
+ bridge.set_mcp_client(mock_client)
+
+ assert bridge.mcp_client == mock_client
+
+ @pytest.mark.asyncio
+ async def test_handle_ping_message(self, bridge, mock_websocket):
+ """Test handling ping message"""
+ ping_message = {"type": "ping"}
+
+ await bridge.handle_websocket_message(ping_message)
+
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "pong"
+ assert "timestamp" in message
+
+ @pytest.mark.asyncio
+ async def test_handle_operation_message_without_client(self, bridge, mock_websocket):
+ """Test handling operation message when MCP client is not set"""
+ operation_message = {
+ "type": "operation",
+ "operation": "list_tools"
+ }
+
+ await bridge.handle_websocket_message(operation_message)
+
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "error"
+ assert "MCP client not initialized" in message["error"]
+
+ @pytest.mark.asyncio
+ async def test_handle_operation_message_with_client(self, bridge, mock_websocket):
+ """Test handling operation message with MCP client"""
+ # Set up mock client
+ mock_client = AsyncMock(spec=MCPClient)
+ bridge.set_mcp_client(mock_client)
+
+ operation_message = {
+ "type": "operation",
+ "operation": "list_tools"
+ }
+
+ with patch('asyncio.create_task') as mock_create_task:
+ await bridge.handle_websocket_message(operation_message)
+
+ # Verify that create_task was called (async operation)
+ mock_create_task.assert_called_once()
+
+ # Verify the task was created with handle_operation call
+ call_args = mock_create_task.call_args[0][0]
+ # The task should be a coroutine, we can't easily verify the exact call
+ # but we can verify create_task was called which is the critical behavior
+
+ @pytest.mark.asyncio
+ async def test_handle_unknown_message_type(self, bridge, mock_websocket):
+ """Test handling unknown message type"""
+ unknown_message = {
+ "type": "unknown_type",
+ "data": "some_data"
+ }
+
+ await bridge.handle_websocket_message(unknown_message)
+
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "error"
+ assert "Unknown message type" in message["error"]
+
+ @pytest.mark.asyncio
+ async def test_handle_elicitation_response_accept(self, bridge, mock_websocket):
+ """Test handling elicitation response with accept action"""
+ # Set up pending elicitation
+ request_id = "test-request-123"
+ future = asyncio.Future()
+ bridge.pending_elicitations[request_id] = future
+
+ response_message = {
+ "type": "elicitation_response",
+ "request_id": request_id,
+ "action": "accept",
+ "data": {"input": "user response"}
+ }
+
+ # Handle the message in a task to avoid blocking
+ async def handle_and_check():
+ await bridge.handle_websocket_message(response_message)
+ # Check that future was resolved
+ assert future.done()
+ result = future.result()
+ assert isinstance(result, ElicitResult)
+ assert result.action == "accept"
+ assert result.content == {"input": "user response"}
+
+ await handle_and_check()
+
+ @pytest.mark.asyncio
+ async def test_handle_elicitation_response_decline(self, bridge, mock_websocket):
+ """Test handling elicitation response with decline action"""
+ # Set up pending elicitation
+ request_id = "test-request-456"
+ future = asyncio.Future()
+ bridge.pending_elicitations[request_id] = future
+
+ response_message = {
+ "type": "elicitation_response",
+ "request_id": request_id,
+ "action": "decline"
+ }
+
+ await bridge.handle_websocket_message(response_message)
+
+ # Check that future was resolved
+ assert future.done()
+ result = future.result()
+ assert isinstance(result, ElicitResult)
+ assert result.action == "decline"
+
+ @pytest.mark.asyncio
+ async def test_handle_elicitation_response_missing_request_id(self, bridge, mock_websocket):
+ """Test handling elicitation response with missing request_id"""
+ response_message = {
+ "type": "elicitation_response",
+ "action": "accept",
+ "data": {"input": "user response"}
+ }
+
+ await bridge.handle_websocket_message(response_message)
+
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "error"
+ assert "Missing request_id" in message["error"]
+
+ @pytest.mark.asyncio
+ async def test_handle_elicitation_response_unknown_request_id(self, bridge, mock_websocket):
+ """Test handling elicitation response with unknown request_id"""
+ response_message = {
+ "type": "elicitation_response",
+ "request_id": "unknown-request-id",
+ "action": "accept",
+ "data": {"input": "user response"}
+ }
+
+ await bridge.handle_websocket_message(response_message)
+
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "operation_error"
+ assert "Unknown elicitation request_id" in message["error"]
+
+ @pytest.mark.asyncio
+ async def test_message_loop_with_valid_json(self, bridge, mock_websocket):
+ """Test message loop with valid JSON messages"""
+ # Add messages to receive
+ mock_websocket.add_message({"type": "ping"})
+
+ # Create a task to run the bridge and stop it after a short delay
+ async def run_and_stop():
+ await asyncio.sleep(0.1) # Let it process one message
+ bridge.stop()
+
+ # Run both tasks concurrently
+ await asyncio.gather(
+ bridge.run(),
+ run_and_stop(),
+ return_exceptions=True
+ )
+
+ # Verify ping was handled
+ assert len(mock_websocket.messages_sent) == 1
+ assert mock_websocket.messages_sent[0]["type"] == "pong"
+
+ @pytest.mark.asyncio
+ async def test_message_loop_with_invalid_json(self, bridge, mock_websocket):
+ """Test message loop with invalid JSON"""
+ # Add invalid JSON message
+ mock_websocket.add_message("invalid json {")
+
+ # Create a task to run the bridge and stop it after a short delay
+ async def run_and_stop():
+ await asyncio.sleep(0.1) # Let it process the invalid message
+ bridge.stop()
+
+ # Run both tasks concurrently
+ await asyncio.gather(
+ bridge.run(),
+ run_and_stop(),
+ return_exceptions=True
+ )
+
+ # Verify error message was sent
+ assert len(mock_websocket.messages_sent) == 1
+ message = mock_websocket.messages_sent[0]
+ assert message["type"] == "error"
+ assert "Invalid message format" in message["error"]
+
+ def test_stop_bridge(self, bridge):
+ """Test stopping the bridge"""
+ assert bridge._running is True
+
+ bridge.stop()
+
+ assert bridge._running is False
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])
diff --git a/python/packages/autogen-studio/tests/test_db_manager.py b/python/packages/autogen-studio/tests/test_db_manager.py
index c2912a7d5..0bd075c5f 100644
--- a/python/packages/autogen-studio/tests/test_db_manager.py
+++ b/python/packages/autogen-studio/tests/test_db_manager.py
@@ -122,7 +122,7 @@ class TestDatabaseOperations:
test_db.upsert(Run(
id=run1_id,
user_id=test_user,
- session_id=session1.id,
+ session_id=session1.id or 1, # Ensure session_id is not None
status=RunStatus.COMPLETE,
task=MessageConfig(content="Task1", source="user").model_dump()
))
@@ -145,7 +145,7 @@ class TestDatabaseOperations:
test_db.upsert(Run(
id=run2_id,
user_id=test_user,
- session_id=session2.id,
+ session_id=session2.id or 2, # Ensure session_id is not None
status=RunStatus.COMPLETE,
task=MessageConfig(content="Task2", source="user").model_dump()
))
diff --git a/python/packages/autogen-studio/tests/test_lite_studio.py b/python/packages/autogen-studio/tests/test_lite_studio.py
new file mode 100644
index 000000000..46d641842
--- /dev/null
+++ b/python/packages/autogen-studio/tests/test_lite_studio.py
@@ -0,0 +1,311 @@
+import os
+import json
+import pytest
+from unittest.mock import patch, Mock, MagicMock
+from typing import Any, cast, Dict, List, Union
+from pathlib import Path
+
+from autogenstudio.lite import LiteStudio
+
+
+def sample_team_file(tmp_path: Path) -> str:
+ """Fixture for creating a sample team JSON file"""
+ team_data: Dict[str, Union[str, List[Any]]] = {
+ "type": "SampleTeam",
+ "name": "Test Team",
+ "description": "A test team for lite mode",
+ "agents": []
+ }
+ team_file = tmp_path / "test_team.json"
+ with open(team_file, 'w') as f:
+ json.dump(team_data, f)
+ return str(team_file)
+
+
+def sample_team_object() -> Dict[str, Union[str, List[Any]]]:
+ """Fixture for sample team object"""
+ return {
+ "type": "TestTeam",
+ "name": "Object Team",
+ "agents": []
+ }
+
+
+def load_team_from_file(file_path: str) -> Dict[str, Any]:
+ """Helper function to load team data from file"""
+ with open(file_path, 'r') as f:
+ return json.load(f)
+
+
+def test_init_with_file_team(sample_team_file: str) -> None:
+ """Test LiteStudio initialization with a team file"""
+ studio = LiteStudio(
+ team=sample_team_file,
+ host="localhost",
+ port=9090,
+ session_name="Test Session"
+ )
+
+ assert studio.host == "localhost"
+ assert studio.port == 9090
+ assert studio.session_name == "Test Session"
+ assert studio.auto_open is True
+ assert studio.team_file_path == os.path.abspath(sample_team_file)
+ assert studio.server_process is None
+
+
+def test_init_with_team_object(sample_team_object: Dict[str, Union[str, List[Any]]]) -> None:
+ """Test LiteStudio initialization with a team object"""
+ studio = LiteStudio(team=sample_team_object, port=9091)
+
+ # Should create a temporary file
+ assert studio.team_file_path is not None
+ assert os.path.exists(studio.team_file_path)
+ assert studio.port == 9091
+
+ # Verify content matches
+ team_data = load_team_from_file(studio.team_file_path)
+ assert team_data == sample_team_object
+
+
+@patch('autogenstudio.gallery.builder.create_default_lite_team')
+def test_init_with_no_team(mock_create_default: MagicMock) -> None:
+ """Test LiteStudio initialization with no team (should create default)"""
+ mock_create_default.return_value = "/tmp/default_team.json"
+
+ with patch('os.path.exists', return_value=True):
+ studio = LiteStudio()
+
+ mock_create_default.assert_called_once()
+ assert studio.team_file_path is not None
+ # Verify default parameters
+ assert studio.host == "127.0.0.1"
+ assert studio.port == 8080
+ assert studio.auto_open is True
+ assert studio.session_name == "Lite Session"
+
+
+def test_init_with_invalid_file() -> None:
+ """Test LiteStudio initialization with invalid team file"""
+ with pytest.raises(FileNotFoundError, match="Team file not found"):
+ LiteStudio(team="/nonexistent/file.json")
+
+
+def test_setup_environment(sample_team_file: str) -> None:
+ """Test environment variable setup"""
+ studio = LiteStudio(team=sample_team_file, host="127.0.0.1", port=8080)
+
+ env_file_path = studio._setup_environment() # type: ignore
+
+ # Read the environment file to verify contents
+ env_vars = {}
+ with open(env_file_path, 'r') as f:
+ for line in f:
+ if '=' in line:
+ key, value = line.strip().split('=', 1)
+ env_vars[key] = value
+
+ expected_vars = {
+ "AUTOGENSTUDIO_HOST": "127.0.0.1",
+ "AUTOGENSTUDIO_PORT": "8080",
+ "AUTOGENSTUDIO_LITE_MODE": "true",
+ "AUTOGENSTUDIO_API_DOCS": "false",
+ "AUTOGENSTUDIO_AUTH_DISABLED": "true",
+ "AUTOGENSTUDIO_DATABASE_URI": "sqlite:///:memory:",
+ }
+
+ for key, value in expected_vars.items():
+ assert key in env_vars
+ assert env_vars[key] == value
+
+
+@patch('uvicorn.run')
+@patch('threading.Thread')
+@patch('webbrowser.open')
+def test_start_foreground(mock_browser: MagicMock, mock_thread: MagicMock, mock_uvicorn: MagicMock, sample_team_file: str) -> None:
+ """Test starting studio in foreground mode"""
+ studio = LiteStudio(team=sample_team_file, auto_open=True)
+
+ studio.start(background=False)
+
+ # Should call uvicorn.run
+ mock_uvicorn.assert_called_once()
+
+ # Should setup browser opening thread
+ mock_thread.assert_called_once()
+
+
+@patch('uvicorn.run')
+@patch('threading.Thread')
+def test_start_background(mock_thread_class: MagicMock, mock_uvicorn: MagicMock, sample_team_file: str) -> None:
+ """Test starting studio in background mode"""
+ studio = LiteStudio(team=sample_team_file)
+
+ # Mock the server thread
+ mock_server_thread = Mock()
+ mock_thread_class.return_value = mock_server_thread
+
+ studio.start(background=True)
+
+ # Should create and start server thread
+ mock_thread_class.assert_called()
+ # Note: start() is called twice - once for browser opening, once for server
+ assert mock_server_thread.start.call_count >= 1
+ assert studio.server_thread == mock_server_thread
+
+
+def test_context_manager(sample_team_file: str) -> None:
+ """Test LiteStudio as context manager"""
+ with patch.object(LiteStudio, 'start') as mock_start:
+ with patch.object(LiteStudio, 'stop') as mock_stop:
+ with LiteStudio(team=sample_team_file) as studio:
+ assert studio is not None
+ mock_start.assert_called_once_with(background=True)
+
+ mock_stop.assert_called_once()
+
+
+def test_stop_with_server_thread(sample_team_file: str) -> None:
+ """Test stopping studio with active server thread"""
+ studio = LiteStudio(team=sample_team_file)
+
+ # Mock server thread
+ mock_thread = Mock()
+ mock_thread.is_alive.return_value = True
+ studio.server_thread = mock_thread
+
+ studio.stop()
+
+ mock_thread.join.assert_called_once_with(timeout=5)
+
+
+@patch('subprocess.run')
+def test_shutdown_port(mock_subprocess: MagicMock) -> None:
+ """Test shutting down a specific port"""
+ # Mock subprocess return with stdout containing PIDs
+ mock_result = Mock()
+ mock_result.returncode = 0
+ mock_result.stdout = "1234\n5678"
+ mock_subprocess.return_value = mock_result
+
+ LiteStudio.shutdown_port(8080)
+
+ # Should attempt to find and kill process on port
+ mock_subprocess.assert_called()
+
+
+@patch('uvicorn.run')
+def test_start_twice_raises_error(mock_uvicorn: MagicMock, sample_team_file: str) -> None:
+ """Test that starting an already running studio raises an error"""
+ studio = LiteStudio(team=sample_team_file)
+
+ # Mock that server is already running
+ studio.server_thread = Mock()
+ studio.server_thread.is_alive.return_value = True
+
+ with pytest.raises(RuntimeError, match="already running"):
+ studio.start()
+
+
+def test_init_with_team_object_with_serialization_methods() -> None:
+ """Test LiteStudio initialization with objects that have serialization methods"""
+
+ # Mock object with dump_component method (like AutoGen teams)
+ class MockTeamWithDumpComponent:
+ def dump_component(self) -> Any:
+ class MockComponent:
+ def model_dump(self) -> Dict[str, Union[str, List[Any]]]:
+ return {"type": "MockTeam", "name": "Serialized Team", "participants": []}
+ return MockComponent()
+
+ mock_team = MockTeamWithDumpComponent()
+ # Cast to Any since the runtime handles this properly
+ studio = LiteStudio(team=cast(Any, mock_team), port=9092)
+
+ # Should create a temporary file with serialized content
+ assert studio.team_file_path is not None
+ assert os.path.exists(studio.team_file_path)
+
+ # Verify content matches serialization
+ team_data = load_team_from_file(studio.team_file_path)
+ assert team_data["type"] == "MockTeam"
+ assert team_data["name"] == "Serialized Team"
+
+
+def test_init_with_team_object_model_dump() -> None:
+ """Test LiteStudio initialization with Pydantic v2 style objects"""
+
+ class MockPydanticTeam:
+ def model_dump(self):
+ return {"type": "PydanticTeam", "name": "Model Dump Team"}
+
+ mock_team = MockPydanticTeam()
+ # Cast to Any since the runtime handles this properly
+ studio = LiteStudio(team=cast(Any, mock_team), port=9093)
+
+ # Verify content
+ team_data = load_team_from_file(studio.team_file_path)
+ assert team_data["type"] == "PydanticTeam"
+ assert team_data["name"] == "Model Dump Team"
+
+
+def test_init_with_unsupported_team_object() -> None:
+ """Test LiteStudio initialization with unsupported team object"""
+
+ class UnsupportedTeam:
+ def some_other_method(self):
+ return "not serializable"
+
+ with pytest.raises(ValueError, match="Cannot serialize team object"):
+ # Cast to Any since we're intentionally testing unsupported type
+ LiteStudio(team=cast(Any, UnsupportedTeam()))
+
+
+def test_init_with_path_object(tmp_path: Path) -> None:
+ """Test LiteStudio initialization with Path object"""
+
+ team_data: Dict[str, Union[str, List[Any]]] = {
+ "type": "PathTeam",
+ "name": "Path Test Team",
+ "agents": []
+ }
+ team_file = tmp_path / "path_team.json"
+ with open(team_file, 'w') as f:
+ json.dump(team_data, f)
+
+ # Use Path object instead of string
+ studio = LiteStudio(team=team_file, port=9094)
+
+ assert studio.team_file_path == str(team_file.absolute())
+ assert os.path.exists(studio.team_file_path)
+
+ # Verify content
+ team_data_loaded = load_team_from_file(studio.team_file_path)
+ assert team_data_loaded == team_data
+
+
+def test_init_with_component_model() -> None:
+ """Test LiteStudio initialization with ComponentModel"""
+
+ # Since ComponentModel is more complex to create directly,
+ # we'll test this by mocking it in the _load_team method
+ team_dict: Dict[str, Union[str, List[Any]]] = {
+ "type": "ComponentTeam",
+ "name": "Component Model Team",
+ "participants": []
+ }
+
+ # Create a mock that behaves like ComponentModel
+ from unittest.mock import Mock
+ mock_component = Mock()
+ mock_component.model_dump.return_value = team_dict
+
+ # Test that it gets handled in the ComponentModel branch
+ studio = LiteStudio(team=team_dict, port=9095) # Use dict instead for now
+
+ # Verify the dict path works (ComponentModel would use same serialization)
+ team_data = load_team_from_file(studio.team_file_path)
+ assert team_data["type"] == "ComponentTeam"
+ assert team_data["name"] == "Component Model Team"
diff --git a/python/uv.lock b/python/uv.lock
index d1fcb990b..8c40183ab 100644
--- a/python/uv.lock
+++ b/python/uv.lock
@@ -837,10 +837,11 @@ dependencies = [
{ name = "anthropic" },
{ name = "autogen-agentchat" },
{ name = "autogen-core" },
- { name = "autogen-ext", extra = ["azure", "magentic-one", "openai"] },
+ { name = "autogen-ext", extra = ["azure", "magentic-one", "mcp", "openai"] },
{ name = "fastapi", extra = ["standard"] },
{ name = "html2text" },
{ name = "loguru" },
+ { name = "mcp" },
{ name = "psycopg" },
{ name = "pydantic" },
{ name = "pydantic-settings" },
@@ -867,11 +868,12 @@ requires-dist = [
{ name = "anthropic" },
{ name = "autogen-agentchat", editable = "packages/autogen-agentchat" },
{ name = "autogen-core", editable = "packages/autogen-core" },
- { name = "autogen-ext", extras = ["azure", "magentic-one", "openai"], editable = "packages/autogen-ext" },
+ { name = "autogen-ext", extras = ["azure", "magentic-one", "mcp", "openai"], editable = "packages/autogen-ext" },
{ name = "fastapi", marker = "extra == 'web'" },
{ name = "fastapi", extras = ["standard"] },
{ name = "html2text" },
{ name = "loguru" },
+ { name = "mcp", specifier = ">=1.11.0" },
{ name = "psycopg" },
{ name = "psycopg", marker = "extra == 'database'" },
{ name = "pydantic" },