Skip to content

A programming framework for agentic AI

Support MCP Elicitation, Sampling, and Roots via new McpSessionHost (#6833)

Tyler Paynec02791282b40
diff --git a/python/packages/autogen-ext/examples/mcp_example_server.py b/python/packages/autogen-ext/examples/mcp_example_server.py
new file mode 100644
index 000000000..07361bc10
--- /dev/null
+++ b/python/packages/autogen-ext/examples/mcp_example_server.py
@@ -0,0 +1,75 @@
+"""From: https://github.com/modelcontextprotocol/python-sdk?tab=readme-ov-file#elicitation"""
+
+from pathlib import Path
+
+from mcp import SamplingMessage
+from mcp.server.fastmcp import Context, FastMCP
+from mcp.types import TextContent
+from pydantic import BaseModel, Field
+
+mcp = FastMCP(name="Elicitation Example")
+
+
+class BookingPreferences(BaseModel):
+ """Schema for collecting user preferences."""
+
+ checkAlternative: bool = Field(description="Would you like to check another time?")
+ alternativeTime: str = Field(
+ description="Alternative time.",
+ )
+
+
+async def book_table(
+ time: str,
+ party_size: int,
+ ctx: Context,
+) -> str:
+ """Book a table with time availability check."""
+ # time unavailable - ask user for alternative
+ result = await ctx.elicit(
+ message=(f"No tables available for {party_size} at {time}. Would you like to try another time?"),
+ schema=BookingPreferences,
+ )
+
+ if result.action == "accept" and result.data:
+ if result.data.checkAlternative:
+ return f"[SUCCESS] Booked for {result.data.alternativeTime}"
+ return "[CANCELLED] No booking made"
+ return "[CANCELLED] Booking cancelled"
+
+
+async def list_dir(path: Path, ctx: Context) -> list[str]:
+ """List the files and directories in path"""
+ roots = await ctx.session.list_roots()
+ for root in roots.roots:
+ root_path = root.uri.path
+ if root_path:
+ root_path = Path(root_path)
+ try:
+ _ = path.relative_to(root_path)
+ return ["Downloads", "Documents", "image.png", "presentation.pptx"]
+ except ValueError:
+ # Skip relative_to failure
+ pass
+ raise ValueError(f"Cannot list_dir in {path} because it is not a child of the available roots.")
+
+
+async def generate_poem(topic: str, ctx: Context) -> str:
+ poem = await ctx.session.create_message(
+ [SamplingMessage(role="user", content=TextContent(type="text", text=f"Write a poem about {topic}."))],
+ max_tokens=100,
+ system_prompt="You are a very creative poet.",
+ temperature=0.8,
+ stop_sequences=["\n\n"],
+ )
+ if isinstance(poem.content, TextContent):
+ return poem.content.text
+ else:
+ raise TypeError(f"Unrecognized message response type {type(poem.content).__name__}")
+
+
+if __name__ == "__main__":
+ mcp.run("stdio")
diff --git a/python/packages/autogen-ext/examples/mcp_session_host_example.py b/python/packages/autogen-ext/examples/mcp_session_host_example.py
new file mode 100644
index 000000000..c3a45c4a9
--- /dev/null
+++ b/python/packages/autogen-ext/examples/mcp_session_host_example.py
@@ -0,0 +1,251 @@
+"""
+Interactive MCP Host Capabilities Demo
+
+This example demonstrates advanced MCP host capabilities including:
+- Sampling: Language model text generation requests from MCP server back to host
+- Elicitation: Interactive user input collection through command-line
+- Roots: File system root listing
+
+The demo is fully interactive and allows you to communicate directly with
+the MCP server through the command line interface.
+"""
+
+import argparse
+import asyncio
+import json
+import logging
+import sys
+from pathlib import Path
+
+import yaml
+from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
+from autogen_agentchat.conditions import MaxMessageTermination
+from autogen_agentchat.teams import RoundRobinGroupChat
+from autogen_agentchat.ui import Console
+from autogen_core.models import ChatCompletionClient
+from autogen_ext.models.openai import OpenAIChatCompletionClient
+from autogen_ext.tools.mcp import (
+ ChatCompletionClientSampler,
+ McpSessionHost,
+ McpWorkbench,
+ StaticRootsProvider,
+ StdioElicitor,
+ StdioServerParams,
+)
+from mcp.types import Root
+from pydantic import FileUrl
+
+# Configure logging
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(message)s", # Clean format for demo output
+)
+logger = logging.getLogger(__name__)
+logging.getLogger("autogen_core").setLevel(logging.WARNING)
+
+
+def load_model_client_from_config(config_path: str) -> ChatCompletionClient:
+ """Load a ChatCompletionClient from a JSON or YAML config file.
+
+ Args:
+ config_path: Path to the JSON or YAML config file
+
+ Returns:
+ ChatCompletionClient: Loaded model client
+
+ Raises:
+ FileNotFoundError: If config file doesn't exist
+ ValueError: If config format is invalid or unsupported file type
+ """
+ config_file = Path(config_path)
+ if not config_file.exists():
+ raise FileNotFoundError(f"Config file not found: {config_path}")
+
+ # Load config based on file extension
+ if config_file.suffix.lower() == ".json":
+ with open(config_file, "r") as f:
+ config_data = json.load(f)
+ elif config_file.suffix.lower() in [".yml", ".yaml"]:
+ with open(config_file, "r") as f:
+ config_data = yaml.safe_load(f)
+ else:
+ raise ValueError(f"Unsupported config file type: {config_file.suffix}. Use .json, .yml, or .yaml")
+
+ if not isinstance(config_data, dict):
+ raise ValueError("Config file must contain a JSON/YAML object")
+
+ logger.info(f"πŸ“„ Loading ChatCompletionClient from config: {config_path}")
+ return ChatCompletionClient.load_component(config_data)
+
+
+async def interactive_mcp_demo(config_path: str | None = None):
+ """Interactive MCP host capabilities demo with command-line interface."""
+ logger.info("🌟 Interactive MCP Host Capabilities Demo")
+ logger.info("=" * 60)
+ logger.info("This demo showcases MCP server-to-host communication:")
+ logger.info("β€’ Sampling: MCP server requests language model generation")
+ logger.info("β€’ Elicitation: MCP server requests user input via AgentElicitor")
+ logger.info("β€’ Roots: MCP server lists available file system roots")
+ logger.info("=" * 60)
+
+ # Setup model client for sampling
+ if config_path:
+ logger.info("βš™οΈ Loading model client from config file...")
+ model_client = load_model_client_from_config(config_path)
+ else:
+ logger.info("βš™οΈ Setting up default OpenAI model client (gpt-4)...")
+ model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
+
+ other_assistant = AssistantAgent(
+ "booking_assistant",
+ model_client=model_client,
+ description="An AI assistant who helps a user book 5pm reservations.",
+ )
+
+ sampler = ChatCompletionClientSampler(model_client)
+
+ # Start runtime and create AgentElicitor that targets the UserProxy
+ logger.info("🎯 Creating StdioElicitor...")
+ elicitor = StdioElicitor()
+
+ roots = StaticRootsProvider(
+ [Root(uri=FileUrl("file:///home"), name="Home"), Root(uri=FileUrl("file:///tmp"), name="Tmp")]
+ )
+
+ # Create host with all capabilities including elicitation
+ logger.info("🏠 Creating MCP session host with sampling, elicitation, and roots support...")
+ host = McpSessionHost(
+ sampler=sampler, # Support sampling via model clicent
+ elicitor=elicitor, # Support elicitation via booking_assistant
+ roots=roots, # support roots in /home and /tmp
+ )
+
+ # Setup workbench with host
+ logger.info("πŸ”§ Creating MCP Workbench for mcp_example_server...")
+ mcp_workbench = McpWorkbench(
+ server_params=StdioServerParams(
+ command=sys.executable,
+ args=[str(Path(__file__).parent / "mcp_example_server.py")],
+ read_timeout_seconds=60,
+ ),
+ host=host,
+ )
+
+ # Create assistant with MCP capabilities
+ assistant = AssistantAgent(
+ "mcp_assistant",
+ model_client=model_client,
+ workbench=mcp_workbench,
+ description="An AI assistant with access to MCP tools that can request sampling and elicitation from the host",
+ )
+
+ # Create RoundRobinGroupChat with the agents
+ logger.info("πŸ”„ Setting up RoundRobinGroupChat...")
+ team = RoundRobinGroupChat(
+ [assistant, other_assistant], termination_condition=MaxMessageTermination(max_messages=2)
+ )
+
+ # Run the team with the initial task
+ tasks = ["Book a table for 2 at 7pm", "Generate a poem about computer protocols.", "ls /home", "ls /bin"]
+ for task in tasks:
+ await team.reset()
+ result = await Console(team.run_stream(task=task))
+
+ logger.info("πŸ’¬ Team conversation:")
+ for message in result.messages:
+ header = f"--- {type(message).__name__.upper()} ---"
+ logger.info(header)
+ logger.info(message.model_dump_json(indent=2))
+
+
+def parse_arguments() -> argparse.Namespace:
+ """Parse command line arguments."""
+ parser = argparse.ArgumentParser(
+ description="Interactive MCP Host Capabilities Demo with AgentElicitor",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ epilog="""
+Examples:
+ # Run with default OpenAI GPT-4 client
+ python mcp_elicitation_example.py
+
+ # Run with custom model client from config
+ python mcp_elicitation_example.py --config model_config.json
+ python mcp_elicitation_example.py --config model_config.yaml
+
+Config file format (JSON/YAML):
+{
+ "component_type": "OpenAIChatCompletionClient",
+ "model": "gpt-4",
+ "api_key": "your-api-key"
+}
+ """,
+ )
+
+ parser.add_argument(
+ "--config",
+ "-c",
+ type=str,
+ help="Path to JSON or YAML config file containing ChatCompletionClient configuration",
+ )
+
+ return parser.parse_args()
+
+
+async def main():
+ """
+ Run the interactive MCP host capabilities demonstration.
+
+ This demo allows direct command-line interaction with an MCP-enabled assistant
+ that can use tools requiring host-side capabilities like sampling and elicitation.
+ """
+ args = parse_arguments()
+
+ try:
+ await interactive_mcp_demo(config_path=args.config)
+ except KeyboardInterrupt:
+ logger.info("\nπŸ‘‹ Demo interrupted by user. Goodbye!")
+ except Exception as e:
+ logger.error(f"❌ Error running demo: {e}")
+ logger.info("Troubleshooting tips:")
+ logger.info("1. Install the everything server:")
+ logger.info(" npm install -g @modelcontextprotocol/server-everything")
+ logger.info("2. Ensure your OpenAI API key is configured")
+ logger.info("3. Check that Node.js and npx are available in your PATH")
+ logger.info("4. Make sure you have internet connectivity for npm package download")
+ if args.config:
+ logger.info("5. Check that your config file exists and contains valid ChatCompletionClient configuration")
+
+
+if __name__ == "__main__":
+ """
+ Interactive MCP Host Capabilities Demo with AgentElicitor
+
+ This demo provides a command-line interface to interact with an MCP-enabled
+ assistant that demonstrates advanced host capabilities:
+
+ πŸ”„ Sampling: MCP server can request language model text generation from the host
+ ❓ Elicitation: MCP server can request interactive user input via AgentElicitor β†’ UserProxy
+ πŸ“ Roots: MCP server can request file system root listings from the host
+
+ Key Features:
+ - AgentElicitor routes elicitation requests from MCP server to UserProxyAgent
+ - Full bidirectional communication between MCP server and AutoGen agents
+ - Interactive command-line interface for real-time demonstration
+
+ Prerequisites:
+ 1. Install the everything reference server:
+ npm install -g @modelcontextprotocol/server-everything
+ 2. Set up your OpenAI API key (required for sampling capability)
+ 3. Ensure Node.js and npx are available in your PATH
+
+ Usage:
+ - Run with default model: python mcp_elicitation_example.py
+ - Run with custom model: python mcp_elicitation_example.py --config model.json
+ - Interact through the command-line interface
+ - Ask the assistant to use MCP tools that demonstrate host capabilities
+ - Watch elicitation requests get routed through the AgentElicitor
+ - Type 'quit' to exit the interactive session
+ """
+
+ # Run the interactive demo
+ asyncio.run(main())
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/__init__.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/__init__.py
index fcf414874..24f818ba5 100644
--- a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/__init__.py
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/__init__.py
@@ -1,6 +1,19 @@
from ._actor import McpSessionActor
from ._config import McpServerParams, SseServerParams, StdioServerParams, StreamableHttpServerParams
from ._factory import mcp_server_tools
+from ._host import (
+ ChatCompletionClientSampler,
+ ChatCompletionClientSamplerConfig,
+ Elicitor,
+ McpSessionHost,
+ RootsProvider,
+ Sampler,
+ StaticRootsProvider,
+ StaticRootsProviderConfig,
+ StdioElicitor,
+ StdioElicitorConfig,
+ StreamElicitor,
+)
from ._session import create_mcp_server_session
from ._sse import SseMcpToolAdapter
from ._stdio import StdioMcpToolAdapter
@@ -19,4 +32,15 @@ __all__ = [
"McpServerParams",
"mcp_server_tools",
"McpWorkbench",
+ "Elicitor",
+ "StdioElicitor",
+ "StdioElicitorConfig",
+ "StreamElicitor",
+ "RootsProvider",
+ "StaticRootsProvider",
+ "StaticRootsProviderConfig",
+ "McpSessionHost",
+ "ChatCompletionClientSampler",
+ "ChatCompletionClientSamplerConfig",
+ "Sampler",
]
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_actor.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_actor.py
index add4de2e5..bf8e45466 100644
--- a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_actor.py
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_actor.py
@@ -1,20 +1,9 @@
import asyncio
import atexit
-import base64
-import io
import logging
from typing import Any, Coroutine, Dict, Mapping, TypedDict
-from autogen_core import Component, ComponentBase, ComponentModel, Image
-from autogen_core.models import (
- AssistantMessage,
- ChatCompletionClient,
- LLMMessage,
- ModelInfo,
- SystemMessage,
- UserMessage,
-)
-from PIL import Image as PILImage
+from autogen_core import Component, ComponentBase
from pydantic import BaseModel
from typing_extensions import Self
@@ -23,6 +12,7 @@ from mcp.client.session import ClientSession
from mcp.shared.context import RequestContext
from ._config import McpServerParams
+from ._host import McpSessionHost
from ._session import create_mcp_server_session
logger = logging.getLogger(__name__)
@@ -39,52 +29,43 @@ McpResult = (
McpFuture = asyncio.Future[McpResult]
-def _parse_sampling_content(
- content: mcp_types.TextContent | mcp_types.ImageContent | mcp_types.AudioContent, model_info: ModelInfo
-) -> str | Image:
- """Convert MCP content types to Autogen content types."""
- if content.type == "text":
- return content.text
- elif content.type == "image":
- if not model_info["vision"]:
- raise ValueError("Sampling model does not support image content.")
- # Decode base64 image data and create PIL Image
- image_data = base64.b64decode(content.data)
- pil_image = PILImage.open(io.BytesIO(image_data))
- return Image.from_pil(pil_image)
- else:
- raise ValueError(f"Unsupported content type: {content.type}")
-
-
-def _parse_sampling_message(message: mcp_types.SamplingMessage, model_info: ModelInfo) -> LLMMessage:
- """Convert MCP sampling messages to Autogen messages."""
- content = _parse_sampling_content(message.content, model_info=model_info)
- if message.role == "user":
- return UserMessage(
- source="user",
- content=[content],
- )
- elif message.role == "assistant":
- assert isinstance(content, str), "Assistant messages only support string content."
- return AssistantMessage(
- source="assistant",
- content=content,
- )
- else:
- raise ValueError(f"Unrecognized message role: {message.role}")
+class McpActorArgs(TypedDict):
+ """Arguments structure for MCP actor command calls.
+ Args:
+ name: Optional name parameter for operations that require it (e.g., tool calls)
+ kargs: Additional keyword arguments for the operation
+ """
-class McpActorArgs(TypedDict):
name: str | None
kargs: Mapping[str, Any]
class McpSessionActorConfig(BaseModel):
+ """Configuration model for MCP session actor components.
+
+ Args:
+ server_params: Parameters for connecting to the MCP server
+ """
+
server_params: McpServerParams
- model_client: ComponentModel | Dict[str, Any] | None = None
class McpSessionActor(ComponentBase[BaseModel], Component[McpSessionActorConfig]):
+ """Actor that manages an MCP session and handles asynchronous MCP operations.
+
+ This actor runs in a separate asyncio task and processes MCP commands through
+ a queue-based system. It handles initialization, tool calls, resource operations,
+ prompt operations, and proper cleanup of the MCP session.
+
+ The actor supports callbacks for sampling and elicitation requests from MCP
+ servers, delegating these to an optional host component.
+
+ Args:
+ server_params: Configuration parameters for the MCP server connection
+ host: Optional host component for handling sampling and elicitation requests
+ """
+
component_type = "mcp_session_actor"
component_config_schema = McpSessionActorConfig
component_provider_override = "autogen_ext.tools.mcp.McpSessionActor"
@@ -93,9 +74,9 @@ class McpSessionActor(ComponentBase[BaseModel], Component[McpSessionActorConfig]
# model_config = ConfigDict(arbitrary_types_allowed=True)
- def __init__(self, server_params: McpServerParams, model_client: ChatCompletionClient | None = None) -> None:
+ def __init__(self, server_params: McpServerParams, host: McpSessionHost | None = None) -> None:
self.server_params: McpServerParams = server_params
- self._model_client = model_client
+ self._host = host
self.name = "mcp_session_actor"
self.description = "MCP session actor"
self._command_queue: asyncio.Queue[Dict[str, Any]] = asyncio.Queue()
@@ -162,55 +143,53 @@ class McpSessionActor(ComponentBase[BaseModel], Component[McpSessionActorConfig]
params: mcp_types.CreateMessageRequestParams,
) -> mcp_types.CreateMessageResult | mcp_types.ErrorData:
"""Handle sampling requests using the provided model client."""
- if self._model_client is None:
+ if self._host is None:
# Return an error when no model client is available
return mcp_types.ErrorData(
code=mcp_types.INVALID_REQUEST,
- message="No model client available for sampling.",
+ message="No host available for sampling.",
data=None,
)
- llm_messages: list[LLMMessage] = []
-
- try:
- if params.systemPrompt:
- llm_messages.append(SystemMessage(content=params.systemPrompt))
-
- for mcp_message in params.messages:
- llm_messages.append(_parse_sampling_message(mcp_message, model_info=self._model_client.model_info))
+ return await self._host.handle_sampling_request(params)
- except Exception as e:
+ async def _elicitation_callback(
+ self,
+ context: RequestContext["ClientSession", Any],
+ params: mcp_types.ElicitRequestParams,
+ ) -> mcp_types.ElicitResult | mcp_types.ErrorData:
+ """Handle elicitation requests using the provided input_func."""
+ if self._host is None:
+ # Return an error when no model client is available
return mcp_types.ErrorData(
- code=mcp_types.INVALID_PARAMS,
- message="Error processing sampling messages.",
- data=f"{type(e).__name__}: {e}",
+ code=mcp_types.INVALID_REQUEST,
+ message="No host available for elicitation.",
+ data=None,
)
- try:
- result = await self._model_client.create(messages=llm_messages)
-
- content = result.content
- if not isinstance(content, str):
- content = str(content)
+ return await self._host.handle_elicit_request(params)
- return mcp_types.CreateMessageResult(
- role="assistant",
- content=mcp_types.TextContent(type="text", text=content),
- model=self._model_client.model_info["family"],
- stopReason=result.finish_reason,
- )
- except Exception as e:
+ async def _list_roots(
+ self, context: RequestContext["ClientSession", Any]
+ ) -> mcp_types.ListRootsResult | mcp_types.ErrorData:
+ """Handle list_roots requests"""
+ if self._host is None:
+ # Return an error when no model client is available
return mcp_types.ErrorData(
- code=mcp_types.INTERNAL_ERROR,
- message="Error sampling from model client.",
- data=f"{type(e).__name__}: {e}",
+ code=mcp_types.INVALID_REQUEST,
+ message="No host available for listing roots.",
+ data=None,
)
+ return await self._host.handle_list_roots_request()
async def _run_actor(self) -> None:
result: McpResult
try:
async with create_mcp_server_session(
- self.server_params, sampling_callback=self._sampling_callback
+ self.server_params,
+ sampling_callback=self._sampling_callback,
+ elicitation_callback=self._elicitation_callback,
+ list_roots_callback=self._list_roots,
) as session:
# Save the initialize result
self._initialize_result = await session.initialize()
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_base.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_base.py
index aabc4dcc9..314dbe15e 100644
--- a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_base.py
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_base.py
@@ -11,7 +11,14 @@ from pydantic import BaseModel
from pydantic.networks import AnyUrl
from mcp import ClientSession, Tool
-from mcp.types import AudioContent, ContentBlock, EmbeddedResource, ImageContent, ResourceLink, TextContent
+from mcp.types import (
+ AudioContent,
+ ContentBlock,
+ EmbeddedResource,
+ ImageContent,
+ ResourceLink,
+ TextContent,
+)
from ._config import McpServerParams
from ._session import create_mcp_server_session
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/README.md b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/README.md
new file mode 100644
index 000000000..bbb638dc2
--- /dev/null
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/README.md
@@ -0,0 +1,236 @@
+# MCP Session Host
+
+The `McpSessionHost` supports MCP Server -> MCP Host requests within the AutoGen ecosystem. By design it should require minimal or no changes to your AutoGen agents, simply provide a host to the `McpWorkbench`.
+
+The following MCP features are supported:
+
+1. **Sampling**: Text generation using language models
+2. **Elicitation**: Interactive user prompting and structured data collection
+3. **Roots**: File system root listing for server access
+
+## Architecture
+
+```mermaid
+flowchart LR
+ %% Source Agent layer
+ subgraph Source_Agent ["Source Agent"]
+ direction TB
+ WB[MCP Workbench]
+ HS[MCP Session Host]
+
+ %% Abstract components
+ subgraph Abstract_Components ["Abstract Components"]
+ R[RootsProvider]
+ S[Sampler]
+ E[Elicitor Type]
+ end
+
+ %% Concrete components
+ subgraph Component_Subclasses ["Concrete Components"]
+ CCCS[ChatCompletionClientSampler]
+ SE[StdioElicitor]
+ SRP[StaticRootsProvider]
+ end
+ end
+
+
+ %% Server layer: tool execution
+ subgraph MCP_Server ["MCP Server"]
+ MS[MCP Server]
+ end
+
+ %% Chat Completion Client
+ CCC[Chat Completion Client]
+
+ %% Flows
+ WB -->|tool call| MS
+ MS -.->|sampling/elicitation/roots requests| WB
+
+ WB -->|sampling/elicitation/roots requests| HS
+
+ %% Sampling via Sampler
+ HS -->|sampling| S
+ S --> CCCS
+ CCCS -->|completion| CCC
+
+ %% Elicitation via Elicitor
+ HS -->|elicitation| E
+ E --> SE
+ SE -->|stdio| U["User"]
+
+ %% Roots via RootsProvider
+ HS -->|roots| R
+ R --> SRP
+```
+
+## Sequence Diagrams
+
+### Normal Tool Calling Flow
+
+```mermaid
+sequenceDiagram
+ participant Assistant as AutoGen Assistant
+ participant Workbench as McpWorkbench
+ participant Server as MCP Server
+ participant ModelClient as ChatCompletionClient
+
+ Assistant->>Workbench: call_tool(tool, args)
+ Workbench->>Server: execute tool
+ Note over Server: Tool execution does not require host resources
+ Server->>Workbench: tool result
+ Workbench->>Assistant: tool execution result
+```
+
+
+### Sampling Request Flow
+
+```mermaid
+sequenceDiagram
+ participant Assistant as AutoGen Assistant
+ participant Workbench as McpWorkbench
+ participant Server as MCP Server
+ participant Host as McpSessionHost
+ participant Sampler as ChatCompletionClientSampler
+ participant ModelClient as ChatCompletionClient
+
+ Assistant->>Workbench: call_tool(tool, args)
+ Workbench->>Server: execute tool
+ Note over Server: Tool execution requires text generation
+ Server->>Workbench: sampling request
+ Workbench->>Host: handle_sampling_request()
+ Host->>Sampler: sample(params)
+ Sampler->>ModelClient: create(messages, extra_args)
+ ModelClient->>Sampler: response with content
+ Sampler->>Host: CreateMessageResult
+ Host->>Workbench: CreateMessageResult
+ Workbench->>Server: sampling response
+ Server->>Workbench: tool result
+ Workbench->>Assistant: tool execution result
+```
+
+### Elicitation Request Flow
+
+```mermaid
+sequenceDiagram
+ participant Assistant as AutoGen Assistant
+ participant Workbench as McpWorkbench
+ participant Server as MCP Server
+ participant Host as McpSessionHost
+ participant Elicitor as StdioElicitor
+ participant User
+
+ Assistant->>Workbench: call_tool(tool, args)
+ Workbench->>Server: execute tool
+ Note over Server: Tool needs user input with structured response
+ Server->>Workbench: ElicitRequest
+ Workbench->>Host: handle_elicit_request()
+ Host->>Elicitor: elicit(params)
+ Elicitor->>User: prompt via stdio
+ User->>Elicitor: response via stdio
+ Elicitor->>Host: elicit result
+ Host->>Workbench: elicit result
+ Workbench->>Server: elicit result
+ Server->>Workbench: tool result
+ Workbench->>Assistant: tool execution result
+```
+
+### List Roots Request Flow
+
+```mermaid
+sequenceDiagram
+ participant Assistant as AutoGen Assistant
+ participant Workbench as McpWorkbench
+ participant Server as MCP Server
+ participant Host as McpSessionHost
+ participant RootsProvider as StaticRootsProvider
+
+ Assistant->>Workbench: call_tool(tool, args)
+ Workbench->>Server: execute tool
+ Note over Server: Tool needs to know available file system roots
+ Server->>Workbench: list_roots request
+ Workbench->>Host: handle_list_roots_request()
+ Host->>RootsProvider: list_roots()
+ RootsProvider->>Host: ListRootsResult with configured roots
+ Host->>Workbench: ListRootsResult
+ Workbench->>Server: roots response
+ Server->>Workbench: tool result with root info
+ Workbench->>Assistant: tool execution result
+```
+
+## Components
+
+### McpSessionHost
+
+The main host-side component that handles server-to-host requests and coordinates with component providers:
+
+- **Sampler**: Handles sampling requests via `Sampler`s (e.g. `ChatCompletionClientSampler`)
+- **Elicitor**: Handles elicitation requests via `Elicitor`s (e.g. `StdioElicitor`, `StreamElicitor`)
+- **RootsProvider**: Provides file system access configuration via `RootsProvider`s (e.g. `StaticRootsProvider`)
+
+### Component Types
+
+#### Samplers
+Handle text generation requests from MCP servers:
+- **ChatCompletionClientSampler**: Routes sampling requests to any `ChatCompletionClient`
+
+#### Elicitors
+Handle structured prompting requests from MCP servers:
+- **StdioElicitor**: Interactive user prompting via standard input/output streams.
+- **StreamElicitor**: Base class for stream-based elicitation
+
+#### RootsProviders
+Manage file system root access for MCP servers:
+- **StaticRootsProvider**: Provides a static list of file system roots
+
+## Usage
+
+### Example
+
+```diff
+from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
+from autogen_agentchat.teams import RoundRobinGroupChat
+from autogen_ext.models.openai import OpenAIChatCompletionClient
+from autogen_ext.tools.mcp import McpWorkbench, StdioServerParams
++ from autogen_ext.tools.mcp import (
++ ChatCompletionClientSampler,
++ McpSessionHost,
++ StaticRootsProvider,
++ StdioElicitor,
++ )
++ from pydantic import FileUrl
++ from mcp.types import Root
+
+# Setup model client
+model_client = OpenAIChatCompletionClient(model="gpt-4o")
+
++ # Create components
++ sampler = ChatCompletionClientSampler(model_client)
++ elicitor = StdioElicitor()
++ roots = StaticRootsProvider([
++ Root(uri=FileUrl("file:///workspace"), name="Workspace"),
++ Root(uri=FileUrl("file:///docs"), name="Documentation"),
++ ])
+
++ # Create host with all capabilities
++ host = McpSessionHost(
++ sampler=sampler, # For sampling requests
++ elicitor=elicitor, # For elicitation requests
++ roots=roots, # For roots requests
++ )
+
+# Setup MCP workbench
+mcp_workbench = McpWorkbench(
+ server_params=StdioServerParams(
+ command="python",
+ args=["your_mcp_server.py"]
+ ),
++ host=host,
+)
+
+# Create MCP-enabled assistant
+assistant = AssistantAgent(
+ "assistant",
+ model_client=model_client,
+ workbench=mcp_workbench,
+)
+```
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/__init__.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/__init__.py
new file mode 100644
index 000000000..510cdd0d8
--- /dev/null
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/__init__.py
@@ -0,0 +1,18 @@
+from ._elicitation import Elicitor, StdioElicitor, StdioElicitorConfig, StreamElicitor
+from ._roots import RootsProvider, StaticRootsProvider, StaticRootsProviderConfig
+from ._sampling import ChatCompletionClientSampler, ChatCompletionClientSamplerConfig, Sampler
+from ._session_host import McpSessionHost
+
+__all__ = [
+ "Elicitor",
+ "StdioElicitor",
+ "StdioElicitorConfig",
+ "StreamElicitor",
+ "RootsProvider",
+ "StaticRootsProvider",
+ "StaticRootsProviderConfig",
+ "McpSessionHost",
+ "ChatCompletionClientSampler",
+ "ChatCompletionClientSamplerConfig",
+ "Sampler",
+]
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_elicitation.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_elicitation.py
new file mode 100644
index 000000000..373f995c2
--- /dev/null
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_elicitation.py
@@ -0,0 +1,127 @@
+import asyncio
+import json
+import sys
+from abc import ABC, abstractmethod
+from typing import TextIO
+
+from autogen_core import (
+ Component,
+ ComponentBase,
+)
+from pydantic import BaseModel
+
+from mcp import types as mcp_types
+
+_ELICITATION_CHOICE_SHORTHANDS = {"a": "accept", "d": "decline", "c": "cancel"}
+
+
+class Elicitor(ABC, ComponentBase[BaseModel]):
+ """Abstract base class for handling MCP elicitation requests.
+
+ Elicitors are responsible for processing elicitation requests from MCP servers,
+ which typically involve prompting for user input, and sometimes require more structured responses.
+ """
+
+ component_type = "mcp_elicitor"
+
+ @abstractmethod
+ async def elicit(self, params: mcp_types.ElicitRequestParams) -> mcp_types.ElicitResult | mcp_types.ErrorData: ...
+
+
+class StreamElicitor(Elicitor):
+ """Handle MCP elicitation requests by reading/writing to TextIO streams."""
+
+ def __init__(self, read_stream: TextIO, write_stream: TextIO, timeout: float | None = None) -> None:
+ self._read_stream = read_stream
+ self._write_stream = write_stream
+ self._timeout = timeout
+
+ def _write(self, text: str) -> None:
+ self._write_stream.writelines(text)
+ self._write_stream.flush()
+
+ async def _read(self) -> str:
+ """
+ Await a single line from `read` without blocking the event loop.
+
+ Returns the raw line including its trailing newline (if any).
+ """
+
+ # Read one line from the provided TextIO in a worker thread
+ coroutine = asyncio.to_thread(self._read_stream.readline)
+ if self._timeout:
+ coroutine = asyncio.wait_for(coroutine, self._timeout)
+ return await coroutine
+
+ async def elicit(self, params: mcp_types.ElicitRequestParams) -> mcp_types.ElicitResult:
+ header = "=== BEGIN MCP ELICITATION REQUEST ==="
+ border = "=" * len(header)
+ header = f"{border}\n{header}\n{border}"
+ prompt = "\n".join(
+ [
+ header,
+ params.message,
+ "Choices:",
+ "\t[a]ccept",
+ "\t[d]ecline",
+ "\t[c]ancel",
+ "Please enter one of the above options: ",
+ ]
+ )
+
+ self._write(prompt)
+
+ try:
+ action = await self._read()
+ action = action.strip().lower()
+ action = _ELICITATION_CHOICE_SHORTHANDS.get(action, action)
+
+ result = mcp_types.ElicitResult.model_validate({"action": action})
+
+ if action == "accept" and params.requestedSchema:
+ prompt = "\n".join(
+ [
+ "Input Schema:",
+ json.dumps(params.requestedSchema, indent=2),
+ "Please enter a JSON string following the above schema: ",
+ ]
+ )
+
+ self._write(prompt)
+
+ content = await self._read()
+
+ result.content = json.loads(content)
+
+ return result
+ finally:
+ footer = "=== END MCP ELICITATION REQUEST ==="
+ border = "=" * len(footer)
+ footer = f"{border}\n{footer}\n{border}"
+ self._write(footer)
+
+
+class StdioElicitorConfig(BaseModel):
+ timeout: float | None
+
+
+class StdioElicitor(StreamElicitor, Component[StdioElicitorConfig]):
+ """Handle MCP elicitation requests by reading/writing to stdio"""
+
+ component_config_schema = StdioElicitorConfig
+ component_provider_override = "autogen_ext.tools.mcp.StdioElicitor"
+
+ def __init__(self, timeout: float | None = None) -> None:
+ super().__init__(sys.stdin, sys.stdout, timeout)
+
+ @property
+ def timeout(self) -> float | None:
+ """Get the timeout value for elicitation operations."""
+ return self._timeout
+
+ def _to_config(self) -> BaseModel:
+ return StdioElicitorConfig(timeout=self._timeout)
+
+ @classmethod
+ def _from_config(cls, config: StdioElicitorConfig) -> "StdioElicitor":
+ return StdioElicitor(timeout=config.timeout)
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_roots.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_roots.py
new file mode 100644
index 000000000..423a9942a
--- /dev/null
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_roots.py
@@ -0,0 +1,41 @@
+from abc import ABC, abstractmethod
+from typing import List, Sequence
+
+from autogen_core import Component, ComponentBase
+from pydantic import BaseModel
+
+from mcp import types as mcp_types
+
+
+class RootsProvider(ABC, ComponentBase[BaseModel]):
+ """A serializable base class for handling callable roots listing."""
+
+ component_type = "mcp_roots_provider"
+
+ @abstractmethod
+ async def list_roots(self) -> mcp_types.ListRootsResult | mcp_types.ErrorData:
+ """List the available roots."""
+ ...
+
+
+class StaticRootsProviderConfig(BaseModel):
+ roots: List[mcp_types.Root]
+
+
+class StaticRootsProvider(RootsProvider, Component[StaticRootsProviderConfig]):
+ component_config_schema = StaticRootsProviderConfig
+ component_provider_override = "autogen_ext.tools.mcp.StaticRootsProvider"
+
+ def __init__(self, roots: Sequence[mcp_types.Root]):
+ self._roots = list(roots)
+
+ async def list_roots(self) -> mcp_types.ListRootsResult:
+ # Return a copy so callers can't mutate our internal list.
+ return mcp_types.ListRootsResult(roots=list(self._roots))
+
+ def _to_config(self) -> BaseModel:
+ return StaticRootsProviderConfig(roots=self._roots)
+
+ @classmethod
+ def _from_config(cls, config: StaticRootsProviderConfig) -> "StaticRootsProvider":
+ return StaticRootsProvider(roots=config.roots)
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_sampling.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_sampling.py
new file mode 100644
index 000000000..44a49ffd4
--- /dev/null
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_sampling.py
@@ -0,0 +1,183 @@
+import base64
+import io
+from abc import ABC, abstractmethod
+from typing import Any, Dict
+
+from autogen_core import Image
+from autogen_core._component_config import Component, ComponentBase, ComponentModel
+from autogen_core.models import (
+ AssistantMessage,
+ ChatCompletionClient,
+ FinishReasons,
+ LLMMessage,
+ ModelInfo,
+ SystemMessage,
+ UserMessage,
+)
+from PIL import Image as PILImage
+from pydantic import BaseModel
+
+from mcp import types as mcp_types
+from mcp.types import StopReason
+
+
+def parse_sampling_content(
+ content: mcp_types.TextContent | mcp_types.ImageContent | mcp_types.AudioContent,
+ model_info: ModelInfo | None = None,
+) -> str | Image:
+ """Convert MCP content types to AutoGen content types.
+
+ Handles text and image content conversion, with vision model validation for images.
+
+ Args:
+ content: MCP content object (text, image, or audio)
+ model_info: Optional model information for vision capability checking
+
+ Returns:
+ Converted content as string or Image object
+
+ Raises:
+ RuntimeError: If image content is provided but model doesn't support vision
+ ValueError: If content type is unsupported
+ """
+ if content.type == "text":
+ return content.text
+ elif content.type == "image":
+ if model_info and not model_info.get("vision", False):
+ model_family = model_info.get("family", "unknown")
+ raise RuntimeError(f"model {model_family} does not support vision.")
+
+ # Decode base64 image data and create PIL Image
+ image_data = base64.b64decode(content.data)
+ pil_image = PILImage.open(io.BytesIO(image_data))
+ return Image.from_pil(pil_image)
+ else:
+ raise ValueError(f"Unsupported content type: {content.type}")
+
+
+def parse_sampling_message(message: mcp_types.SamplingMessage, model_info: ModelInfo | None = None) -> LLMMessage:
+ """Convert MCP sampling messages to AutoGen LLM messages.
+
+ Args:
+ message: MCP sampling message with role and content
+ model_info: Optional model information for content parsing
+
+ Returns:
+ Converted AutoGen LLM message (UserMessage or AssistantMessage)
+
+ Raises:
+ ValueError: If message role is not recognized
+ AssertionError: If assistant message content is not text
+ """
+ content = parse_sampling_content(message.content, model_info=model_info)
+ if message.role == "user":
+ return UserMessage(
+ source="user",
+ content=[content],
+ )
+ elif message.role == "assistant":
+ assert isinstance(content, str), "Assistant messages only support string content."
+ return AssistantMessage(
+ source="assistant",
+ content=content,
+ )
+ else:
+ raise ValueError(f"Unrecognized message role: {message.role}")
+
+
+def finish_reason_to_stop_reason(finish_reason: FinishReasons) -> StopReason:
+ """Convert AutoGen finish reasons to MCP stop reasons.
+
+ Args:
+ finish_reason: AutoGen completion finish reason
+
+ Returns:
+ Corresponding MCP stop reason
+ """
+ if finish_reason == "stop":
+ return "endTurn"
+ elif finish_reason == "length":
+ return "maxTokens"
+ else:
+ return finish_reason
+
+
+def create_request_params_to_extra_create_args(params: mcp_types.CreateMessageRequestParams) -> Dict[str, Any]:
+ """Convert MCP request parameters to AutoGen extra create arguments.
+
+ Args:
+ params: MCP message creation request parameters
+
+ Returns:
+ Dictionary of extra arguments for AutoGen chat completion client
+ """
+ # TODO: Need to support all ChatCompletionClients
+ extra_create_args: dict[str, Any] = {"max_tokens": params.maxTokens}
+ if params.temperature is not None:
+ extra_create_args["temperature"] = params.temperature
+ if params.stopSequences is not None:
+ extra_create_args["stop"] = params.stopSequences
+ return extra_create_args
+
+
+class Sampler(ABC, ComponentBase[BaseModel]):
+ component_type = "mcp_sampler"
+
+ @abstractmethod
+ async def sample(
+ self, params: mcp_types.CreateMessageRequestParams
+ ) -> mcp_types.CreateMessageResult | mcp_types.ErrorData: ...
+
+
+class ChatCompletionClientSamplerConfig(BaseModel):
+ client_config: ComponentModel | Dict[str, Any]
+
+
+class ChatCompletionClientSampler(Sampler, Component[ChatCompletionClientSamplerConfig]):
+ component_config_schema = ChatCompletionClientSamplerConfig
+ component_provider_override = "autogen_ext.tools.mcp.ChatCompletionClientSampler"
+
+ def __init__(self, model_client: ChatCompletionClient):
+ self._model_client = model_client
+
+ async def sample(
+ self, params: mcp_types.CreateMessageRequestParams
+ ) -> mcp_types.CreateMessageResult | mcp_types.ErrorData:
+ # Convert MCP messages to AutoGen format using existing parser
+ autogen_messages: list[LLMMessage] = []
+
+ # Add system prompt if provided
+ if params.systemPrompt:
+ autogen_messages.append(SystemMessage(content=params.systemPrompt))
+
+ # Parse sampling messages
+ for msg in params.messages:
+ autogen_messages.append(parse_sampling_message(msg, model_info=self._model_client.model_info))
+
+ # Use the model client to generate a response
+ extra_create_args = create_request_params_to_extra_create_args(params)
+
+ response = await self._model_client.create(messages=autogen_messages, extra_create_args=extra_create_args)
+
+ # Extract text content from response
+ if isinstance(response.content, str):
+ response_text = response.content
+ else:
+ from pydantic_core import to_json
+
+ # Handle function calls - convert to string representation
+ response_text = to_json(response.content).decode()
+
+ return mcp_types.CreateMessageResult(
+ role="assistant",
+ content=mcp_types.TextContent(type="text", text=response_text),
+ model=self._model_client.model_info["family"],
+ stopReason=finish_reason_to_stop_reason(response.finish_reason),
+ )
+
+ def _to_config(self) -> BaseModel:
+ return ChatCompletionClientSamplerConfig(client_config=self._model_client.dump_component())
+
+ @classmethod
+ def _from_config(cls, config: ChatCompletionClientSamplerConfig) -> "ChatCompletionClientSampler":
+ return ChatCompletionClientSampler(model_client=ChatCompletionClient.load_component(config.client_config))
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_session_host.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_session_host.py
new file mode 100644
index 000000000..9cbd7605e
--- /dev/null
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/_session_host.py
@@ -0,0 +1,205 @@
+from typing import Any, Dict
+
+from autogen_core import Component, ComponentBase, ComponentModel
+from pydantic import BaseModel
+
+from mcp import types as mcp_types
+
+from ._elicitation import Elicitor
+from ._roots import RootsProvider
+from ._sampling import Sampler
+
+
+class McpSessionHostConfig(BaseModel):
+ """Configuration for MCP session host components.
+
+ Args:
+ model_client: Optional chat completion client for sampling requests
+ elicitor: Optional elicitor component for handling elicitation requests
+ roots: Optional list of file system roots or roots provider
+ """
+
+ sampler: ComponentModel | Dict[str, Any] | None
+ elicitor: ComponentModel | Dict[str, Any] | None
+ roots: ComponentModel | Dict[str, Any] | None
+
+
+class McpSessionHost(ComponentBase[BaseModel], Component[McpSessionHostConfig]):
+ """Host component that provides MCP server capabilities.
+
+ This host acts as the client-side Host for MCP sessions, handling requests
+ from MCP servers for text generation (sampling), user prompting (elicitation),
+ and file system root listing. It coordinates with model clients and elicitors
+ to provide these capabilities.
+
+ The host supports three main MCP server capabilities:
+ - Sampling: Text generation using a language model via chat completion client
+ - Elicitation: Structured prompting and response collection via elicitors
+ - Roots: Listing available file system roots for server access
+
+ Args:
+ model_client: Optional chat completion client for handling sampling requests
+ roots: Optional sequence of roots or callable returning roots for file system access
+ elicitor: Optional elicitor for handling elicitation requests
+
+ Example:
+ Complete setup with MCP capabilities including sampling and elicitation::
+
+ from autogen_agentchat.agents import AssistantAgent
+ from autogen_ext.models.openai import OpenAIChatCompletionClient
+ from autogen_ext.tools.mcp import (
+ ChatCompletionClientSampler,
+ McpSessionHost,
+ McpWorkbench,
+ StaticRootsProvider,
+ StdioElicitor,
+ StdioServerParams,
+ )
+ from pydantic import FileUrl
+
+ from mcp.types import Root
+
+ # Setup model client for sampling
+ model_client = OpenAIChatCompletionClient(model="gpt-4o")
+ sampler = ChatCompletionClientSampler(model_client)
+
+ # Create elicitor that prompts for user input over stdio
+ elicitor = StdioElicitor()
+
+ # Provide static roots in the host system
+ roots = StaticRootsProvider(
+ [Root(uri=FileUrl("file:///home"), name="Home"), Root(uri=FileUrl("file:///tmp"), name="Tmp")]
+ )
+
+ # Create MCP session host with sampling, elicitation, and list_roots capabilities
+ # If you want to support roots, import or define Root and FileUrl, then uncomment the roots line below
+ host = McpSessionHost(
+ sampler=sampler, # Support sampling via model client
+ elicitor=elicitor, # Support elicitation via user_proxy
+ roots=roots,
+ )
+
+ # Setup MCP workbench with your server
+ mcp_workbench = McpWorkbench(
+ server_params=StdioServerParams(command="python", args=["your_mcp_server.py"]),
+ host=host, # Add the host here
+ )
+
+ # Create MCP-enabled assistant
+ mcp_assistant = AssistantAgent(
+ "mcp_assistant",
+ model_client=model_client,
+ workbench=mcp_workbench,
+ )
+
+ # Now the AssistantAgent can support MCP servers that request sampling, elicitation, and roots!
+ """
+
+ component_type = "mcp_session_host"
+ component_config_schema = McpSessionHostConfig
+ component_provider_override = "autogen_ext.tools.mcp.McpSessionHost"
+
+ def __init__(
+ self,
+ sampler: Sampler | None = None,
+ roots: RootsProvider | None = None,
+ elicitor: Elicitor | None = None,
+ ):
+ """Initialize the MCP session host.
+
+ Args:
+ sampler: Optional sampler handling sampling requests.
+ roots: Optional roots provider for returning roots for file system access.
+ elicitor: Optional elicitor for handling elicitation requests.
+ """
+ self._sampler = sampler
+ self._roots = roots
+ self._elicitor = elicitor
+
+ async def handle_sampling_request(
+ self, params: mcp_types.CreateMessageRequestParams
+ ) -> mcp_types.CreateMessageResult | mcp_types.ErrorData:
+ """Handle a sampling request from MCP servers.
+
+ Converts MCP messages to AutoGen format and uses the configured sampler (if any)
+ to generate a response.
+
+ Args:
+ params: The sampling request containing message creation parameters.
+
+ Returns:
+ A sampling response with the generated message or error data.
+ """
+ if self._sampler is None:
+ return mcp_types.ErrorData(
+ code=mcp_types.INVALID_REQUEST,
+ message="No model client available for sampling requests",
+ )
+
+ try:
+ response = await self._sampler.sample(params)
+ return response
+ except Exception as e:
+ return mcp_types.ErrorData(
+ code=mcp_types.INTERNAL_ERROR,
+ message=f"Sampling request failed: {str(e)}",
+ )
+
+ async def handle_elicit_request(
+ self, params: mcp_types.ElicitRequestParams
+ ) -> mcp_types.ElicitResult | mcp_types.ErrorData:
+ """Handle an elicitation request from MCP servers.
+
+ Forwards the elicitation request to the configured elicitor for processing.
+ The elicitor handles the structured prompting and response collection.
+
+ Args:
+ params: The elicitation request containing prompts and parameters.
+
+ Returns:
+ An elicitation response with the structured result or error data.
+ """
+ if self._elicitor is None:
+ return mcp_types.ErrorData(
+ code=mcp_types.INVALID_REQUEST,
+ message="No elicitor configured for this host",
+ )
+
+ try:
+ return await self._elicitor.elicit(params)
+ except Exception as e:
+ return mcp_types.ErrorData(
+ code=mcp_types.INTERNAL_ERROR,
+ message=f"Elicitation request failed: {str(e)}",
+ )
+
+ async def handle_list_roots_request(self) -> mcp_types.ListRootsResult | mcp_types.ErrorData:
+ """Handle a list roots request from MCP servers.
+
+ Returns the configured file system roots that are available for server access.
+
+ Returns:
+ A list roots response containing available roots or error data.
+ """
+ if self._roots is None:
+ return mcp_types.ErrorData(code=mcp_types.INVALID_REQUEST, message="Host does not support listing roots")
+ else:
+ try:
+ return await self._roots.list_roots()
+ except Exception as e:
+ return mcp_types.ErrorData(code=mcp_types.INTERNAL_ERROR, message=f"Caught error listing roots: {e}")
+
+ def _to_config(self) -> BaseModel:
+ return McpSessionHostConfig(
+ sampler=self._sampler.dump_component() if self._sampler else None,
+ elicitor=self._elicitor.dump_component() if self._elicitor else None,
+ roots=self._roots.dump_component() if self._roots else None,
+ )
+
+ @classmethod
+ def _from_config(cls, config: McpSessionHostConfig) -> "McpSessionHost":
+ return cls(
+ sampler=Sampler.load_component(config.sampler) if config.sampler else None,
+ elicitor=Elicitor.load_component(config.elicitor) if config.elicitor else None,
+ roots=RootsProvider.load_component(config.roots) if config.roots else None,
+ )
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_session.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_session.py
index 04ea17fed..922e2e101 100644
--- a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_session.py
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_session.py
@@ -3,7 +3,7 @@ from datetime import timedelta
from typing import AsyncGenerator
from mcp import ClientSession
-from mcp.client.session import SamplingFnT
+from mcp.client.session import ElicitationFnT, ListRootsFnT, SamplingFnT
from mcp.client.sse import sse_client
from mcp.client.stdio import stdio_client
from mcp.client.streamable_http import streamablehttp_client
@@ -13,7 +13,10 @@ from ._config import McpServerParams, SseServerParams, StdioServerParams, Stream
@asynccontextmanager
async def create_mcp_server_session(
- server_params: McpServerParams, sampling_callback: SamplingFnT | None = None
+ server_params: McpServerParams,
+ sampling_callback: SamplingFnT | None = None,
+ elicitation_callback: ElicitationFnT | None = None,
+ list_roots_callback: ListRootsFnT | None = None,
) -> AsyncGenerator[ClientSession, None]:
"""Create an MCP client session for the given server parameters."""
if isinstance(server_params, StdioServerParams):
@@ -23,6 +26,8 @@ async def create_mcp_server_session(
write_stream=write,
read_timeout_seconds=timedelta(seconds=server_params.read_timeout_seconds),
sampling_callback=sampling_callback,
+ elicitation_callback=elicitation_callback,
+ list_roots_callback=list_roots_callback,
) as session:
yield session
elif isinstance(server_params, SseServerParams):
@@ -32,6 +37,8 @@ async def create_mcp_server_session(
write_stream=write,
read_timeout_seconds=timedelta(seconds=server_params.sse_read_timeout),
sampling_callback=sampling_callback,
+ elicitation_callback=elicitation_callback,
+ list_roots_callback=list_roots_callback,
) as session:
yield session
elif isinstance(server_params, StreamableHttpServerParams):
@@ -51,5 +58,7 @@ async def create_mcp_server_session(
write_stream=write,
read_timeout_seconds=timedelta(seconds=server_params.sse_read_timeout),
sampling_callback=sampling_callback,
+ elicitation_callback=elicitation_callback,
+ list_roots_callback=list_roots_callback,
) as session:
yield session
diff --git a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_workbench.py b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_workbench.py
index ff12f0d07..49d225461 100644
--- a/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_workbench.py
+++ b/python/packages/autogen-ext/src/autogen_ext/tools/mcp/_workbench.py
@@ -4,7 +4,6 @@ import warnings
from typing import Any, Dict, List, Literal, Mapping, Optional
from autogen_core import CancellationToken, Component, ComponentModel, Image, trace_tool_span
-from autogen_core.models import ChatCompletionClient
from autogen_core.tools import (
ImageResultContent,
ParametersSchema,
@@ -32,12 +31,13 @@ from mcp.types import (
from ._actor import McpSessionActor
from ._config import McpServerParams, SseServerParams, StdioServerParams, StreamableHttpServerParams
+from ._host import McpSessionHost
class McpWorkbenchConfig(BaseModel):
server_params: McpServerParams
tool_overrides: Dict[str, ToolOverride] = Field(default_factory=dict)
- model_client: ComponentModel | Dict[str, Any] | None = None
+ host: ComponentModel | Dict[str, Any] | None = None
class McpWorkbenchState(BaseModel):
@@ -71,11 +71,11 @@ class McpWorkbench(Workbench, Component[McpWorkbenchConfig]):
* - Prompts
- list_prompts, get_prompt
* - Sampling
- - Optional support via model_client
+ - Optional support via McpSessionHost
* - Roots
- - not supported
+ - Optional support via McpSessionHost
* - Ellicitation
- - not supported
+ - Optional support via McpSessionHost
Args:
server_params (McpServerParams): The parameters to connect to the MCP server.
@@ -240,11 +240,10 @@ class McpWorkbench(Workbench, Component[McpWorkbenchConfig]):
self,
server_params: McpServerParams,
tool_overrides: Optional[Dict[str, ToolOverride]] = None,
- model_client: ChatCompletionClient | None = None,
+ host: McpSessionHost | None = None,
) -> None:
self._server_params = server_params
self._tool_overrides = tool_overrides or {}
- self._model_client = model_client
# Build reverse mapping from override names to original names for call_tool
self._override_name_to_original: Dict[str, str] = {}
@@ -260,6 +259,8 @@ class McpWorkbench(Workbench, Component[McpWorkbenchConfig]):
)
self._override_name_to_original[override_name] = original_name
+ self._host = host
+
# self._session: ClientSession | None = None
self._actor: McpSessionActor | None = None
self._actor_loop: asyncio.AbstractEventLoop | None = None
@@ -466,7 +467,7 @@ class McpWorkbench(Workbench, Component[McpWorkbenchConfig]):
return # Already initialized, no need to start again
if isinstance(self._server_params, (StdioServerParams, SseServerParams, StreamableHttpServerParams)):
- self._actor = McpSessionActor(self._server_params, model_client=self._model_client)
+ self._actor = McpSessionActor(self._server_params, host=self._host)
await self._actor.initialize()
self._actor_loop = asyncio.get_event_loop()
else:
@@ -490,19 +491,17 @@ class McpWorkbench(Workbench, Component[McpWorkbenchConfig]):
pass
def _to_config(self) -> McpWorkbenchConfig:
- model_client_config = None
- if self._model_client is not None:
- model_client_config = self._model_client.dump_component()
+ host_config = self._host.dump_component() if self._host else None
return McpWorkbenchConfig(
- server_params=self._server_params, tool_overrides=self._tool_overrides, model_client=model_client_config
+ server_params=self._server_params, tool_overrides=self._tool_overrides, host=host_config
)
@classmethod
def _from_config(cls, config: McpWorkbenchConfig) -> Self:
- model_client = None
- if config.model_client is not None:
- model_client = ChatCompletionClient.load_component(config.model_client)
- return cls(server_params=config.server_params, tool_overrides=config.tool_overrides, model_client=model_client)
+ host = None
+ if config.host is not None:
+ host = McpSessionHost.load_component(config.host)
+ return cls(server_params=config.server_params, tool_overrides=config.tool_overrides, host=host)
def __del__(self) -> None:
# Ensure the actor is stopped when the workbench is deleted
diff --git a/python/packages/autogen-ext/tests/mcp_server_comprehensive.py b/python/packages/autogen-ext/tests/mcp_server_comprehensive.py
index 7a7615e08..97477df6b 100644
--- a/python/packages/autogen-ext/tests/mcp_server_comprehensive.py
+++ b/python/packages/autogen-ext/tests/mcp_server_comprehensive.py
@@ -2,7 +2,8 @@ import asyncio
import json
import logging
from datetime import datetime
-from typing import Any, Dict, Optional
+from pathlib import Path
+from typing import Any, Dict, Literal, Optional
from mcp import PromptsCapability, ResourcesCapability, ServerCapabilities, ToolsCapability
from mcp.server import Server
@@ -14,10 +15,11 @@ from mcp.types import (
PromptArgument,
PromptMessage,
Resource,
+ SamplingMessage,
TextContent,
Tool,
)
-from pydantic import AnyUrl
+from pydantic import AnyUrl, BaseModel
# Configure logging
logging.basicConfig(level=logging.INFO)
@@ -45,173 +47,311 @@ class SimpleMcpServer:
self.server: Server[object] = Server("simple-mcp-server")
self.register_handlers() # type: ignore[no-untyped-call]
- def register_handlers(self) -> None:
- """Register all MCP handlers."""
+ async def list_prompts(self) -> list[Prompt]:
+ """List available prompts."""
+ return [
+ Prompt(
+ name="code_review",
+ description="Generate a comprehensive code review for a given piece of code",
+ arguments=[
+ PromptArgument(
+ name="code",
+ description="The code to review",
+ required=True,
+ ),
+ PromptArgument(
+ name="language",
+ description="Programming language of the code",
+ required=True,
+ ),
+ ],
+ ),
+ Prompt(
+ name="documentation",
+ description="Generate documentation for code or APIs",
+ arguments=[
+ PromptArgument(
+ name="content",
+ description="The content to document",
+ required=True,
+ ),
+ ],
+ ),
+ ]
- # Prompts
- @self.server.list_prompts() # type: ignore[no-untyped-call,misc]
- async def list_prompts() -> list[Prompt]: # pyright: ignore[reportUnusedFunction]
- """List available prompts."""
- return [
- Prompt(
- name="code_review",
- description="Generate a comprehensive code review for a given piece of code",
- arguments=[
- PromptArgument(
- name="code",
- description="The code to review",
- required=True,
- ),
- PromptArgument(
- name="language",
- description="Programming language of the code",
- required=True,
- ),
- ],
- ),
- Prompt(
- name="documentation",
- description="Generate documentation for code or APIs",
- arguments=[
- PromptArgument(
- name="content",
- description="The content to document",
- required=True,
+ async def get_prompt(self, name: str, arguments: Optional[Dict[str, str]] = None) -> GetPromptResult:
+ """Get a specific prompt with arguments."""
+ if not arguments:
+ arguments = {}
+
+ if name == "code_review":
+ code = arguments.get("code", "// No code provided")
+ language = arguments.get("language", "unknown")
+
+ return GetPromptResult(
+ description=f"Code review for {language} code",
+ messages=[
+ PromptMessage(
+ role="user",
+ content=TextContent(
+ type="text",
+ text=f"Please review this {language} code:\n\n```{language}\n{code}\n```",
),
- ],
- ),
- ]
+ ),
+ ],
+ )
- @self.server.get_prompt() # type: ignore[no-untyped-call,misc]
- async def get_prompt(name: str, arguments: Optional[Dict[str, str]] = None) -> GetPromptResult: # pyright: ignore[reportUnusedFunction]
- """Get a specific prompt with arguments."""
- if not arguments:
- arguments = {}
-
- if name == "code_review":
- code = arguments.get("code", "// No code provided")
- language = arguments.get("language", "unknown")
-
- return GetPromptResult(
- description=f"Code review for {language} code",
- messages=[
- PromptMessage(
- role="user",
- content=TextContent(
- type="text",
- text=f"Please review this {language} code:\n\n```{language}\n{code}\n```",
- ),
+ elif name == "documentation":
+ content = arguments.get("content", "No content provided")
+
+ return GetPromptResult(
+ description="Documentation generation",
+ messages=[
+ PromptMessage(
+ role="user",
+ content=TextContent(
+ type="text",
+ text=f"Please generate documentation for:\n\n{content}",
),
- ],
+ ),
+ ],
+ )
+
+ else:
+ raise ValueError(f"Unknown prompt: {name}")
+
+ async def list_resources(self) -> list[Resource]:
+ """List available resources."""
+ return [
+ Resource(
+ uri=AnyUrl("file:///company/users.json"),
+ name="Company Users",
+ description="List of all company users",
+ mimeType="application/json",
+ ),
+ Resource(
+ uri=AnyUrl("file:///company/projects.json"),
+ name="Active Projects",
+ description="Current projects",
+ mimeType="application/json",
+ ),
+ ]
+
+ async def read_resource(self, uri: AnyUrl) -> str:
+ """Read a specific resource."""
+ uri_str = str(uri)
+
+ if uri_str == "file:///company/users.json":
+ return json.dumps(SAMPLE_DATA["users"], indent=2)
+
+ elif uri_str == "file:///company/projects.json":
+ return json.dumps(SAMPLE_DATA["projects"], indent=2)
+
+ else:
+ raise ValueError(f"Unknown resource: {uri_str}")
+
+ async def list_tools(self) -> list[Tool]:
+ """List available tools."""
+ return [
+ Tool(
+ name="echo",
+ description="Echo back the input text",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "text": {
+ "type": "string",
+ "description": "Text to echo back",
+ }
+ },
+ "required": ["text"],
+ },
+ ),
+ Tool(
+ name="get_time",
+ description="Get the current time",
+ inputSchema={
+ "type": "object",
+ "properties": {},
+ },
+ ),
+ Tool(
+ name="order_dish",
+ description="Order a dish from available options",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "dish": {
+ "type": "string",
+ "enum": ["pizza", "pasta", "burger", "sushi", "tacos"],
+ "description": "The dish to order",
+ }
+ },
+ "required": ["dish"],
+ },
+ ),
+ Tool(
+ name="generate_poem",
+ description="Generate a short poem about a given topic using sampling",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "topic": {
+ "type": "string",
+ "description": "The topic for the poem",
+ }
+ },
+ "required": ["topic"],
+ },
+ ),
+ Tool(
+ name="ls",
+ description="List files and directories in a given path (only allowed in root subdirectories)",
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "The directory path to list",
+ }
+ },
+ "required": ["path"],
+ },
+ ),
+ ]
+
+ async def call_tool(self, name: str, arguments: Optional[Dict[str, Any]] = None) -> list[TextContent]:
+ """Call a specific tool."""
+ if not arguments:
+ arguments = {}
+
+ if name == "echo":
+ text = arguments.get("text", "")
+ return [
+ TextContent(
+ type="text",
+ text=f"Echo: {text}",
)
+ ]
- elif name == "documentation":
- content = arguments.get("content", "No content provided")
-
- return GetPromptResult(
- description="Documentation generation",
- messages=[
- PromptMessage(
- role="user",
- content=TextContent(
- type="text",
- text=f"Please generate documentation for:\n\n{content}",
- ),
- ),
- ],
+ elif name == "get_time":
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ return [
+ TextContent(
+ type="text",
+ text=f"Current time: {current_time}",
)
+ ]
+
+ elif name == "order_dish":
+ dish = arguments.get("dish", "")
+
+ class Order(BaseModel):
+ dish: Literal["pizza", "pasta", "burger", "sushi", "tacos"]
+ quantity: int = 1
+ result = await self.server.request_context.session.elicit(
+ f"{dish} is sold out. Please pick another option.",
+ requestedSchema=Order.model_json_schema(),
+ )
+
+ if result.action == "accept":
+ order = Order.model_validate(result.content)
+
+ return [TextContent(type="text", text=f"You ordered {order.quantity} {order.dish}")]
+ elif result.action == "decline":
+ return [TextContent(type="text", text="You declined to change your order.")]
else:
- raise ValueError(f"Unknown prompt: {name}")
+ return [TextContent(type="text", text="You cancelled request.")]
- # Resources
- @self.server.list_resources() # type: ignore[no-untyped-call,misc]
- async def list_resources() -> list[Resource]: # pyright: ignore[reportUnusedFunction]
- """List available resources."""
- return [
- Resource(
- uri=AnyUrl("file:///company/users.json"),
- name="Company Users",
- description="List of all company users",
- mimeType="application/json",
- ),
- Resource(
- uri=AnyUrl("file:///company/projects.json"),
- name="Active Projects",
- description="Current projects",
- mimeType="application/json",
- ),
+ elif name == "generate_poem":
+ topic = arguments.get("topic", "")
+
+ prompt = f"Write a short poem about {topic}"
+
+ message_result = await self.server.request_context.session.create_message(
+ messages=[
+ SamplingMessage(
+ role="user",
+ content=TextContent(type="text", text=prompt),
+ )
+ ],
+ max_tokens=100,
+ temperature=0.6,
+ stop_sequences=["\n\n"],
+ system_prompt="You are a createive poet.",
+ )
+
+ if (
+ message_result.content
+ and hasattr(message_result.content, "type")
+ and message_result.content.type == "text"
+ ):
+ return [TextContent(type="text", text=message_result.content.text)]
+ return [TextContent(type="text", text=str(message_result.content))]
+
+ elif name == "ls":
+ path = arguments.get("path", "")
+
+ roots = await self.server.request_context.session.list_roots()
+
+ target_path = Path(path).resolve()
+
+ is_allowed = False
+ for root in roots.roots:
+ if root.uri.path is None:
+ continue
+ root_path = Path(root.uri.path).resolve()
+ try:
+ target_path.relative_to(root_path)
+ is_allowed = True
+ break
+ except ValueError:
+ continue
+
+ if not is_allowed:
+ return [TextContent(type="text", text=f"Error: Permission denied accessing '{path}'.")]
+
+ simulated_files = [
+ "config/",
+ "data/",
+ "logs/",
+ "README.md",
+ "app.py",
+ "requirements.txt",
]
- @self.server.read_resource() # type: ignore[no-untyped-call,misc]
- async def read_resource(uri: AnyUrl) -> str: # pyright: ignore[reportUnusedFunction]
- """Read a specific resource."""
- uri_str = str(uri)
+ return [TextContent(type="text", text="\n".join(simulated_files))]
- if uri_str == "file:///company/users.json":
- return json.dumps(SAMPLE_DATA["users"], indent=2)
+ else:
+ raise ValueError(f"Unknown tool: {name}")
- elif uri_str == "file:///company/projects.json":
- return json.dumps(SAMPLE_DATA["projects"], indent=2)
+ def register_handlers(self) -> None:
+ """Register all MCP handlers."""
- else:
- raise ValueError(f"Unknown resource: {uri_str}")
+ @self.server.list_prompts() # type: ignore[no-untyped-call,misc]
+ async def list_prompts() -> list[Prompt]: # pyright: ignore[reportUnusedFunction]
+ return await self.list_prompts()
+
+ @self.server.get_prompt() # type: ignore[no-untyped-call,misc]
+ async def get_prompt(name: str, arguments: Optional[Dict[str, str]] = None) -> GetPromptResult: # pyright: ignore[reportUnusedFunction]
+ return await self.get_prompt(name, arguments)
+
+ @self.server.list_resources() # type: ignore[no-untyped-call,misc]
+ async def list_resources() -> list[Resource]: # pyright: ignore[reportUnusedFunction]
+ return await self.list_resources()
+
+ @self.server.read_resource() # type: ignore[no-untyped-call,misc]
+ async def read_resource(uri: AnyUrl) -> str: # pyright: ignore[reportUnusedFunction]
+ return await self.read_resource(uri)
- # Tools
@self.server.list_tools() # type: ignore[no-untyped-call,misc]
async def list_tools() -> list[Tool]: # pyright: ignore[reportUnusedFunction]
- """List available tools."""
- return [
- Tool(
- name="echo",
- description="Echo back the input text",
- inputSchema={
- "type": "object",
- "properties": {
- "text": {
- "type": "string",
- "description": "Text to echo back",
- }
- },
- "required": ["text"],
- },
- ),
- Tool(
- name="get_time",
- description="Get the current time",
- inputSchema={
- "type": "object",
- "properties": {},
- },
- ),
- ]
+ return await self.list_tools()
@self.server.call_tool() # type: ignore[no-untyped-call,misc]
async def call_tool(name: str, arguments: Optional[Dict[str, Any]] = None) -> list[TextContent]: # pyright: ignore[reportUnusedFunction]
- """Call a specific tool."""
- if not arguments:
- arguments = {}
-
- if name == "echo":
- text = arguments.get("text", "")
- return [
- TextContent(
- type="text",
- text=f"Echo: {text}",
- )
- ]
-
- elif name == "get_time":
- current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- return [
- TextContent(
- type="text",
- text=f"Current time: {current_time}",
- )
- ]
-
- else:
- raise ValueError(f"Unknown tool: {name}")
+ return await self.call_tool(name, arguments)
async def run(self) -> None:
"""Run the MCP server."""
diff --git a/python/packages/autogen-ext/tests/tools/test_mcp_actor.py b/python/packages/autogen-ext/tests/tools/test_mcp_actor.py
index 939b8e857..042310a28 100644
--- a/python/packages/autogen-ext/tests/tools/test_mcp_actor.py
+++ b/python/packages/autogen-ext/tests/tools/test_mcp_actor.py
@@ -3,24 +3,20 @@
import asyncio
import atexit
import json
+import sys
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, AsyncGenerator, Callable, Generator
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from autogen_core import Image
from autogen_core.models import (
CreateResult,
- ModelInfo,
RequestUsage,
- UserMessage,
)
from autogen_ext.tools.mcp import StdioServerParams, StreamableHttpServerParams
from autogen_ext.tools.mcp._actor import (
McpSessionActor,
- _parse_sampling_content, # pyright: ignore[reportPrivateUsage]
- _parse_sampling_message, # pyright: ignore[reportPrivateUsage]
)
from mcp import types as mcp_types
from mcp.shared.context import RequestContext
@@ -30,7 +26,7 @@ from mcp.shared.context import RequestContext
original_atexit_register = atexit.register
-def mock_atexit_register(func: Callable[[], None]) -> None:
+def mock_atexit_register(func: Callable[[], None], *args: Any, **kwargs: Any) -> None:
"""Mock atexit.register to prevent registration during tests."""
pass
@@ -51,6 +47,25 @@ def mcp_server_params() -> StdioServerParams:
)
+async def get_expected_tool_count() -> int:
+ """Get the expected number of tools by importing and examining the comprehensive server."""
+ # Add the parent directory to the path to import the server
+ parent_dir = str(Path(__file__).parent.parent)
+ if parent_dir not in sys.path:
+ sys.path.append(parent_dir)
+
+ try:
+ # Import and instantiate the server to get the tools
+ from mcp_server_comprehensive import SimpleMcpServer
+
+ server = SimpleMcpServer()
+ expected_tools = await server.list_tools()
+ return len(expected_tools)
+ except Exception:
+ # Fallback - return 5 if we can't dynamically determine
+ return 5
+
+
@pytest.fixture
def mock_model_client() -> MagicMock:
"""Mock model client for testing."""
@@ -95,116 +110,6 @@ def mock_model_client_with_vision() -> MagicMock:
return model_client
-def test_parse_sampling_content_unsupported_image_without_vision() -> None:
- """Test _parse_sampling_content raises error for image content when model doesn't support vision (line 56)."""
- model_info: ModelInfo = {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- image_content = mcp_types.ImageContent(
- type="image",
- data="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
- mimeType="image/png",
- )
-
- with pytest.raises(ValueError, match="Sampling model does not support image content"):
- _parse_sampling_content(image_content, model_info)
-
-
-def test_parse_sampling_content_with_vision_support() -> None:
- """Test _parse_sampling_content works with vision-enabled model."""
- model_info: ModelInfo = {
- "vision": True,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- image_content = mcp_types.ImageContent(
- type="image",
- data="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
- mimeType="image/png",
- )
-
- result = _parse_sampling_content(image_content, model_info)
- assert isinstance(result, Image)
-
-
-def test_parse_sampling_content_text() -> None:
- """Test _parse_sampling_content with text content."""
- model_info: ModelInfo = {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- text_content = mcp_types.TextContent(type="text", text="Hello world")
-
- result = _parse_sampling_content(text_content, model_info)
- assert result == "Hello world"
-
-
-def test_parse_sampling_content_unknown_type() -> None:
- """Test _parse_sampling_content raises error for unknown content type."""
- model_info: ModelInfo = {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- # Create a mock content with unknown type
- unknown_content = MagicMock()
- unknown_content.type = "unknown"
-
- with pytest.raises(ValueError, match="Unsupported content type"):
- _parse_sampling_content(unknown_content, model_info)
-
-
-def test_parse_sampling_message_unrecognized_role() -> None:
- """Test _parse_sampling_message raises error for unrecognized role (lines 67-74)."""
- model_info: ModelInfo = {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- # Create a mock message with invalid role by bypassing type checking
- message = MagicMock()
- message.role = "system" # Invalid role that should trigger the error
- message.content = mcp_types.TextContent(type="text", text="Hello")
-
- with pytest.raises(ValueError, match="Unrecognized message role: system"):
- _parse_sampling_message(message, model_info)
-
-
-def test_parse_sampling_message_assistant_with_non_string_content() -> None:
- """Test _parse_sampling_message with assistant message containing non-string content."""
- model_info: ModelInfo = {
- "vision": True,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- # Create image content for assistant message (which should fail)
- image_content = mcp_types.ImageContent(
- type="image",
- data="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
- mimeType="image/png",
- )
- message = mcp_types.SamplingMessage(role="assistant", content=image_content)
-
- # This should raise an AssertionError because assistant messages only support string content
- with pytest.raises(AssertionError, match="Assistant messages only support string content"):
- _parse_sampling_message(message, model_info)
-
-
@pytest.mark.asyncio
async def test_call_when_not_active() -> None:
"""Test call method raises error when actor is not active (line 110)."""
@@ -359,6 +264,18 @@ async def test_read_resource_without_uri() -> None:
# actor._command_queue = original_queue # type: ignore[reportPrivateUsage]
+async def test_get_prompt_without_name() -> None:
+ """Test get_prompt raises error when name is not provided (line 94)."""
+ actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]))
+ actor._active = True # type: ignore[reportPrivateUsage]
+ actor._actor_task = MagicMock() # type: ignore[reportPrivateUsage]
+ actor._actor_task.done.return_value = False # type: ignore[reportPrivateUsage]
+
+ with pytest.raises(ValueError, match="name is required for get_prompt"):
+ await actor.call("get_prompt", {"name": None, "kargs": {}})
+
+
@pytest.mark.asyncio
async def test_call_unknown_command_type() -> None:
"""Test call method raises error for unknown command type (line 147)."""
@@ -384,9 +301,9 @@ async def test_close_when_not_active() -> None:
@pytest.mark.asyncio
-async def test_sampling_callback_without_model_client() -> None:
- """Test sampling callback returns error when no model client is available (line 194)."""
- actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]), model_client=None)
+async def test_sampling_callback_without_host() -> None:
+ """Test sampling callback returns error when no host is available (lines 119-127)."""
+ actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]))
mock_context = MagicMock(spec=RequestContext)
params = mcp_types.CreateMessageRequestParams(
@@ -398,65 +315,94 @@ async def test_sampling_callback_without_model_client() -> None:
assert isinstance(result, mcp_types.ErrorData)
assert result.code == mcp_types.INVALID_REQUEST
- assert "No model client available" in result.message
+ assert "No host available for sampling" in result.message
@pytest.mark.asyncio
-async def test_sampling_callback_message_processing_error() -> None:
- """Test sampling callback handles message processing errors (lines 226-227, 229-233)."""
- # Create a model client for the actor
- model_client = MagicMock()
- model_client.model_info = {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
-
- actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]), model_client=model_client)
+async def test_elicitation_callback_without_host() -> None:
+ """Test elicitation callback returns error when no host is available (lines 135-143)."""
+ actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]))
mock_context = MagicMock(spec=RequestContext)
+ params = mcp_types.ElicitRequestParams(message="Test elicitation message", requestedSchema={"type": "object"})
- # Create a valid SamplingMessage but with invalid role that will cause parsing error
- # We'll patch the message after creation to bypass Pydantic validation
- valid_message = mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))
- # Now change the role to something invalid that will cause _parse_sampling_message to fail
- valid_message.role = "invalid_role" # type: ignore
-
- params = mcp_types.CreateMessageRequestParams(
- messages=[valid_message],
- maxTokens=100,
- )
-
- result = await actor._sampling_callback(mock_context, params) # type: ignore[reportPrivateUsage]
+ result = await actor._elicitation_callback(mock_context, params) # type: ignore[reportPrivateUsage]
assert isinstance(result, mcp_types.ErrorData)
- assert result.code == mcp_types.INVALID_PARAMS
- assert "Error processing sampling messages" in result.message
+ assert result.code == mcp_types.INVALID_REQUEST
+ assert "No host available for elicitation" in result.message
@pytest.mark.asyncio
-async def test_sampling_callback_model_client_error() -> None:
- """Test sampling callback handles model client errors (lines 235-239)."""
- failing_model_client = MagicMock()
- failing_model_client.model_info = {"vision": False, "family": "test-model"}
- failing_model_client.create = AsyncMock(side_effect=Exception("Model API error"))
-
- actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]), model_client=failing_model_client)
+async def test_list_roots_callback_without_host() -> None:
+ """Test list_roots callback returns error when no host is available (lines 149-156)."""
+ actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]))
mock_context = MagicMock(spec=RequestContext)
- params = mcp_types.CreateMessageRequestParams(
- messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
- maxTokens=100,
- )
- result = await actor._sampling_callback(mock_context, params) # type: ignore[reportPrivateUsage]
+ result = await actor._list_roots(mock_context) # type: ignore[reportPrivateUsage]
assert isinstance(result, mcp_types.ErrorData)
- assert result.code == mcp_types.INTERNAL_ERROR
- assert "Error sampling from model client" in result.message
- assert "Model API error" in str(result.data)
+ assert result.code == mcp_types.INVALID_REQUEST
+ assert "No host available for listing roots" in result.message
+
+
+# @pytest.mark.asyncio
+# async def test_sampling_callback_message_processing_error() -> None:
+# """Test sampling callback handles message processing errors (lines 226-227, 229-233)."""
+# # Create a model client for the actor
+# model_client = MagicMock()
+# model_client.model_info = {
+# "vision": False,
+# "function_calling": False,
+# "json_output": False,
+# "family": "test-model",
+# "structured_output": False,
+# }
+
+# actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]), model_client=model_client)
+
+# mock_context = MagicMock(spec=RequestContext)
+
+# # Create a valid SamplingMessage but with invalid role that will cause parsing error
+# # We'll patch the message after creation to bypass Pydantic validation
+# valid_message = mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))
+# # Now change the role to something invalid that will cause _parse_sampling_message to fail
+# valid_message.role = "invalid_role" # type: ignore
+
+# params = mcp_types.CreateMessageRequestParams(
+# messages=[valid_message],
+# maxTokens=100,
+# )
+
+# result = await actor._sampling_callback(mock_context, params) # type: ignore[reportPrivateUsage]
+
+# assert isinstance(result, mcp_types.ErrorData)
+# assert result.code == mcp_types.INVALID_PARAMS
+# assert "Error processing sampling messages" in result.message
+
+
+# @pytest.mark.asyncio
+# async def test_sampling_callback_model_client_error() -> None:
+# """Test sampling callback handles model client errors (lines 235-239)."""
+# failing_model_client = MagicMock()
+# failing_model_client.model_info = {"vision": False, "family": "test-model"}
+# failing_model_client.create = AsyncMock(side_effect=Exception("Model API error"))
+
+# actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]), model_client=failing_model_client)
+
+# mock_context = MagicMock(spec=RequestContext)
+# params = mcp_types.CreateMessageRequestParams(
+# messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
+# maxTokens=100,
+# )
+
+# result = await actor._sampling_callback(mock_context, params) # type: ignore[reportPrivateUsage]
+
+# assert isinstance(result, mcp_types.ErrorData)
+# assert result.code == mcp_types.INTERNAL_ERROR
+# assert "Error sampling from model client" in result.message
+# assert "Model API error" in str(result.data)
@pytest.mark.asyncio
@@ -470,7 +416,10 @@ async def test_run_actor_exception_handling() -> None:
# Create a mock session that will raise exceptions by modifying our mock session
@asynccontextmanager
async def mock_failing_session(
- server_params: Any, sampling_callback: Any = None
+ server_params: Any,
+ sampling_callback: Any = None,
+ elicitation_callback: Any = None,
+ list_roots_callback: Any = None,
) -> AsyncGenerator[MagicMock, None]:
mock_session = MagicMock()
mock_session.initialize = AsyncMock(
@@ -780,13 +729,12 @@ async def test_initialize_result_property() -> None:
async def test_actor_initialization() -> None:
"""Test actor initialization sets up correctly."""
server_params = StdioServerParams(command="echo", args=["test"])
- model_client = MagicMock()
- actor = McpSessionActor(server_params, model_client=model_client)
+ # TODO: Add McpSessionHost
+ actor = McpSessionActor(server_params)
# Check initial state
assert actor.server_params == server_params
- assert actor._model_client == model_client # type: ignore[reportPrivateUsage]
assert actor.name == "mcp_session_actor"
assert actor.description == "MCP session actor"
assert not actor._active # type: ignore[reportPrivateUsage]
@@ -871,7 +819,8 @@ async def test_actor_basic_functionality(mcp_server_params: Any) -> None:
# Test listing tools
tools_future = await actor.call("list_tools")
tools_result: mcp_types.ListToolsResult = await tools_future # type: ignore
- assert len(tools_result.tools) == 2 # echo and get_time
+ expected_tool_count = await get_expected_tool_count()
+ assert len(tools_result.tools) == expected_tool_count
tool_names = [tool.name for tool in tools_result.tools]
assert "echo" in tool_names
assert "get_time" in tool_names
@@ -964,36 +913,37 @@ async def test_actor_tool_failure_handling(mcp_server_params: Any) -> None:
await actor.close()
-async def test_actor_with_model_client_sampling(mcp_server_params: Any, mock_model_client: Any) -> None:
- """Test actor with model client for sampling operations."""
- actor = McpSessionActor(mcp_server_params, model_client=mock_model_client)
+# TODO: Use McpSessionhost
+# @pytest.mark.asyncio
+# async def test_actor_with_model_client_sampling(mcp_server_params: Any, mock_model_client: Any) -> None:
+# """Test actor with model client for sampling operations."""
+# actor = McpSessionActor(mcp_server_params, model_client=mock_model_client)
- try:
- await actor.initialize()
- await asyncio.sleep(0.1)
+# try:
+# await actor.initialize()
+# await asyncio.sleep(0.1)
- # Test sampling callback functionality
- mock_context = MagicMock(spec=RequestContext)
- params = mcp_types.CreateMessageRequestParams(
- messages=[
- mcp_types.SamplingMessage(
- role="user", content=mcp_types.TextContent(type="text", text="Hello from test")
- )
- ],
- maxTokens=100,
- )
+# # Test sampling callback functionality
+# mock_context = MagicMock(spec=RequestContext)
+# params = mcp_types.CreateMessageRequestParams(
+# messages=[
+# mcp_types.SamplingMessage(
+# role="user", content=mcp_types.TextContent(type="text", text="Hello from test")
+# )
+# ],
+# maxTokens=100,
+# )
- result = await actor._sampling_callback(mock_context, params) # type: ignore[reportPrivateUsage]
+# result = await actor._sampling_callback(mock_context, params) # type: ignore[reportPrivateUsage]
- assert isinstance(result, mcp_types.CreateMessageResult)
- assert result.role == "assistant"
- assert isinstance(result.content, mcp_types.TextContent)
- assert result.content.text == "Mock response"
- assert result.model == "test-model"
+# assert isinstance(result, mcp_types.CreateMessageResult)
+# assert result.role == "assistant"
+# assert isinstance(result.content, mcp_types.TextContent)
+# assert result.content.text == "Mock response"
+# assert result.model == "test-model"
- finally:
- await actor.close()
+# finally:
+# await actor.close()
# Integration tests with real MCP server
@@ -1011,7 +961,8 @@ async def test_actor(mcp_server_params: Any) -> None:
# Test listing tools
tools_future = await actor.call("list_tools")
tools_result: mcp_types.ListToolsResult = await tools_future # type: ignore
- assert len(tools_result.tools) == 2 # echo and get_time
+ expected_tool_count = await get_expected_tool_count()
+ assert len(tools_result.tools) == expected_tool_count
tool_names = [tool.name for tool in tools_result.tools]
assert "echo" in tool_names
assert "get_time" in tool_names
@@ -1136,89 +1087,6 @@ def clean_actor() -> Generator[Callable[..., McpSessionActor], None, None]:
actor._actor_task.cancel() # type: ignore[reportPrivateUsage]
-async def test_sampling_callback_with_system_prompt() -> None:
- """Test sampling callback with systemPrompt parameter (line 177)."""
- model_client = MagicMock()
- model_client.model_info = {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- model_client.create = AsyncMock(
- return_value=CreateResult(
- content="Mock response",
- finish_reason="stop",
- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
- cached=False,
- )
- )
-
- actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]), model_client=model_client)
-
- mock_context = MagicMock(spec=RequestContext)
- params = mcp_types.CreateMessageRequestParams(
- messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
- maxTokens=100,
- systemPrompt="You are a helpful assistant.",
- )
-
- result = await actor._sampling_callback(mock_context, params) # type: ignore[reportPrivateUsage]
-
- assert isinstance(result, mcp_types.CreateMessageResult)
- assert result.role == "assistant"
- assert isinstance(result.content, mcp_types.TextContent)
- assert result.content.text == "Mock response"
-
- # Verify that the model client was called with the system prompt
- model_client.create.assert_called_once()
- call_args = model_client.create.call_args[1]
- messages = call_args["messages"]
- assert len(messages) == 2 # SystemMessage + UserMessage
- assert messages[0].content == "You are a helpful assistant."
-
-
-async def test_sampling_callback_with_non_string_content() -> None:
- """Test sampling callback when model returns non-string content (line 194)."""
- model_client = MagicMock()
- model_client.model_info = {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- # Mock the model to return a non-string content
- non_string_content = {"data": "complex object"}
- model_client.create = AsyncMock(
- return_value=CreateResult(
- content=str(non_string_content), # Convert to string for valid content
- finish_reason="stop",
- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
- cached=False,
- )
- )
-
- actor = McpSessionActor(StdioServerParams(command="echo", args=["test"]), model_client=model_client)
-
- mock_context = MagicMock(spec=RequestContext)
- params = mcp_types.CreateMessageRequestParams(
- messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
- maxTokens=100,
- )
-
- result = await actor._sampling_callback(mock_context, params) # type: ignore[reportPrivateUsage]
-
- assert isinstance(result, mcp_types.CreateMessageResult)
- assert result.role == "assistant"
- assert isinstance(result.content, mcp_types.TextContent)
- # Should be converted to string
- assert result.content.text == "{'data': 'complex object'}"
-
-
@pytest.mark.asyncio
async def test_run_actor_all_command_types_exception_handling() -> None:
"""Test _run_actor exception handling for all command types (lines 232-233, 238-239, 244-245, 250-251, 256-263)."""
@@ -1227,7 +1095,10 @@ async def test_run_actor_all_command_types_exception_handling() -> None:
# Create a mock session that will raise exceptions for all command types
@asynccontextmanager
async def mock_failing_session(
- server_params: Any, sampling_callback: Any = None
+ server_params: Any,
+ sampling_callback: Any = None,
+ elicitation_callback: Any = None,
+ list_roots_callback: Any = None,
) -> AsyncGenerator[MagicMock, None]:
mock_session = MagicMock()
mock_session.initialize = AsyncMock(
@@ -1256,7 +1127,7 @@ async def test_run_actor_all_command_types_exception_handling() -> None:
# Give it a moment to initialize
await asyncio.sleep(0.05)
- # Test all command types that can raise exceptions
+ # Test all command types that can raise exceptions (including line 212)
commands_to_test: list[dict[str, Any]] = [
{"type": "call_tool", "name": "test_tool", "args": {}},
{"type": "read_resource", "uri": "test://resource"},
@@ -1264,7 +1135,7 @@ async def test_run_actor_all_command_types_exception_handling() -> None:
{"type": "list_tools"},
{"type": "list_prompts"},
{"type": "list_resources"},
- {"type": "list_resource_templates"},
+ {"type": "list_resource_templates"}, # This covers line 212
]
futures: list[asyncio.Future[Any]] = []
@@ -1341,23 +1212,6 @@ async def test_close_with_shutdown_await() -> None:
actor.close = original_close # type: ignore[method-assign]
-def test_parse_sampling_message_user_role() -> None:
- """Test _parse_sampling_message with user role (line 69)."""
- model_info: ModelInfo = {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- message = mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello user"))
-
- result = _parse_sampling_message(message, model_info)
-
- assert isinstance(result, UserMessage)
- assert result.content == ["Hello user"]
-
-
@pytest.mark.asyncio
async def test_call_tool_command_queuing() -> None:
"""Test call_tool command queuing (line 140)."""
@@ -1396,21 +1250,3 @@ async def test_call_tool_command_queuing() -> None:
# Restore original queue
actor._command_queue = original_queue # type: ignore[reportPrivateUsage]
-
-
-def test_parse_sampling_message_user_role_branch() -> None:
- """Test _parse_sampling_message with user role (line 69)."""
- model_info: ModelInfo = {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
- message = mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello user test"))
-
- result = _parse_sampling_message(message, model_info)
-
- # This specifically tests the user role branch (line 69)
- assert isinstance(result, UserMessage)
- assert result.content == ["Hello user test"]
diff --git a/python/packages/autogen-ext/tests/tools/test_mcp_host.py b/python/packages/autogen-ext/tests/tools/test_mcp_host.py
new file mode 100644
index 000000000..a2655e8e9
--- /dev/null
+++ b/python/packages/autogen-ext/tests/tools/test_mcp_host.py
@@ -0,0 +1,964 @@
+"""Tests for McpSessionHost to cover MCP host functionality."""
+
+import atexit
+from pathlib import Path
+from typing import Any, Callable
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from autogen_core import FunctionCall
+from autogen_core.models import (
+ CreateResult,
+ ModelInfo,
+ RequestUsage,
+ UserMessage,
+)
+from autogen_ext.tools.mcp import (
+ ChatCompletionClientSampler,
+ McpSessionHost,
+ StaticRootsProvider,
+ StdioElicitor,
+ StreamElicitor,
+)
+from autogen_ext.tools.mcp._config import StdioServerParams
+from autogen_ext.tools.mcp._host._sampling import (
+ finish_reason_to_stop_reason,
+ parse_sampling_content,
+ parse_sampling_message,
+)
+from mcp import types as mcp_types
+
+# Monkey patch to prevent atexit handlers from being registered during tests
+# This prevents the test suite from hanging during shutdown
+original_atexit_register = atexit.register
+
+
+def mock_atexit_register(func: Callable[[], None], *args: Any, **kwargs: Any) -> None:
+ """Mock atexit.register to prevent registration during tests."""
+ del func, args, kwargs # Mark as used
+
+
+# Apply the monkey patch
+atexit.register = mock_atexit_register # type: ignore[assignment]
+
+
+def mock_model_client() -> MagicMock:
+ """Mock model client for testing."""
+ model_client = MagicMock()
+ model_client.model_info = {
+ "vision": False,
+ "function_calling": False,
+ "json_output": False,
+ "family": "test-model",
+ "structured_output": False,
+ }
+ model_client.create = AsyncMock(
+ return_value=CreateResult(
+ content="Mock response",
+ finish_reason="stop",
+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
+ cached=False,
+ )
+ )
+ return model_client
+
+
+def mock_model_client_with_vision() -> MagicMock:
+ """Mock model client with vision support for testing."""
+ model_client = MagicMock()
+ model_client.model_info = {
+ "vision": True,
+ "function_calling": False,
+ "json_output": False,
+ "family": "test-vision-model",
+ "structured_output": False,
+ }
+ model_client.create = AsyncMock(
+ return_value=CreateResult(
+ content="Mock response",
+ finish_reason="stop",
+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
+ cached=False,
+ )
+ )
+ return model_client
+
+
+def test_parse_sampling_message_assistant_with_string_content() -> None:
+ """Test _parse_sampling_message with assistant message containing string content (line 61)."""
+ model_info: ModelInfo = {
+ "vision": False,
+ "function_calling": False,
+ "json_output": False,
+ "family": "test-model",
+ "structured_output": False,
+ }
+ # Create string content for assistant message
+ text_content = mcp_types.TextContent(type="text", text="Hello, I'm an assistant")
+ message = mcp_types.SamplingMessage(role="assistant", content=text_content)
+
+ result = parse_sampling_message(message, model_info)
+
+ from autogen_core.models import AssistantMessage
+
+ assert isinstance(result, AssistantMessage)
+ assert result.content == "Hello, I'm an assistant"
+ assert result.source == "assistant"
+
+
+def test_finish_reason_to_stop_reason_length() -> None:
+ """Test _finish_reason_to_stop_reason with 'length' finish reason (lines 72-75)."""
+ result = finish_reason_to_stop_reason("length")
+ assert result == "maxTokens"
+
+
+def test_finish_reason_to_stop_reason_other() -> None:
+ """Test _finish_reason_to_stop_reason with other finish reasons (line 75)."""
+ # Test with a custom finish reason that should be returned as-is
+ result = finish_reason_to_stop_reason("content_filter")
+ assert result == "content_filter"
+
+
+def test_finish_reason_to_stop_reason_stop() -> None:
+ """Test _finish_reason_to_stop_reason with 'stop' finish reason."""
+ result = finish_reason_to_stop_reason("stop")
+ assert result == "endTurn"
+
+
+# McpSessionHost integration tests
+async def test_mcp_session_host_sampling_request(mock_model_client: Any) -> None:
+ """Test McpSessionHost handles sampling requests correctly."""
+ sampler = ChatCompletionClientSampler(mock_model_client)
+ host = McpSessionHost(sampler=sampler)
+
+ params = mcp_types.CreateMessageRequestParams(
+ messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
+ maxTokens=100,
+ )
+
+ result = await host.handle_sampling_request(params)
+
+ assert isinstance(result, mcp_types.CreateMessageResult)
+ assert result.role == "assistant"
+ assert isinstance(result.content, mcp_types.TextContent)
+ assert result.content.text == "Mock response"
+ assert result.model == "test-model"
+
+
+async def test_mcp_session_host_sampling_request_no_sampler() -> None:
+ """Test McpSessionHost returns error when no sampler available."""
+ host = McpSessionHost(sampler=None)
+
+ params = mcp_types.CreateMessageRequestParams(
+ messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
+ maxTokens=100,
+ )
+
+ result = await host.handle_sampling_request(params)
+
+ assert isinstance(result, mcp_types.ErrorData)
+ assert result.code == mcp_types.INVALID_REQUEST
+ assert "No model client available for sampling requests" in result.message
+
+
+async def test_mcp_session_host_sampling_request_with_system_prompt(mock_model_client: Any) -> None:
+ """Test McpSessionHost handles sampling requests with system prompt."""
+ sampler = ChatCompletionClientSampler(mock_model_client)
+ host = McpSessionHost(sampler=sampler)
+
+ params = mcp_types.CreateMessageRequestParams(
+ messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
+ maxTokens=100,
+ systemPrompt="You are a helpful assistant.",
+ )
+
+ result = await host.handle_sampling_request(params)
+
+ assert isinstance(result, mcp_types.CreateMessageResult)
+ # Verify that the model client was called with system message
+ mock_model_client.create.assert_called_once()
+ call_args = mock_model_client.create.call_args[1]
+ messages = call_args["messages"]
+ assert len(messages) == 2 # SystemMessage + UserMessage
+ assert messages[0].content == "You are a helpful assistant."
+
+
+async def test_mcp_session_host_sampling_request_error_handling(mock_model_client: Any) -> None:
+ """Test McpSessionHost handles sampling errors correctly."""
+ # Configure model client to raise an exception
+ mock_model_client.create = AsyncMock(side_effect=Exception("Model API error"))
+ sampler = ChatCompletionClientSampler(mock_model_client)
+ host = McpSessionHost(sampler=sampler)
+
+ params = mcp_types.CreateMessageRequestParams(
+ messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
+ maxTokens=100,
+ )
+
+ result = await host.handle_sampling_request(params)
+
+ assert isinstance(result, mcp_types.ErrorData)
+ assert result.code == mcp_types.INTERNAL_ERROR
+ assert "Sampling request failed" in result.message
+
+
+async def test_mcp_session_host_elicit_request() -> None:
+ """Test McpSessionHost handles elicit requests correctly."""
+ # Create a mock elicitor
+ mock_elicitor = MagicMock(spec=StdioElicitor)
+ mock_elicitor.elicit = AsyncMock(
+ return_value=mcp_types.ElicitResult(
+ action="accept", content={"reasoning": "Test reasoning", "answer": "Test answer"}
+ )
+ )
+
+ host = McpSessionHost(elicitor=mock_elicitor)
+
+ params = mcp_types.ElicitRequestParams(message="Test elicitation message", requestedSchema={"type": "object"})
+
+ result = await host.handle_elicit_request(params)
+
+ assert isinstance(result, mcp_types.ElicitResult)
+ assert result.action == "accept"
+ assert result.content is not None
+ assert result.content["reasoning"] == "Test reasoning"
+ assert result.content["answer"] == "Test answer"
+ mock_elicitor.elicit.assert_called_once_with(params)
+
+
+async def test_mcp_session_host_elicit_request_no_elicitor() -> None:
+ """Test McpSessionHost returns error when no elicitor available."""
+ host = McpSessionHost(elicitor=None)
+
+ params = mcp_types.ElicitRequestParams(message="Test elicitation message", requestedSchema={"type": "object"})
+
+ result = await host.handle_elicit_request(params)
+
+ assert isinstance(result, mcp_types.ErrorData)
+ assert result.code == mcp_types.INVALID_REQUEST
+ assert "No elicitor configured" in result.message
+
+
+async def test_mcp_session_host_elicit_request_error_handling() -> None:
+ """Test McpSessionHost handles elicit errors correctly."""
+ # Create a mock elicitor that raises an exception
+ mock_elicitor = MagicMock(spec=StdioElicitor)
+ mock_elicitor.elicit = AsyncMock(side_effect=Exception("Elicitor error"))
+
+ host = McpSessionHost(elicitor=mock_elicitor)
+
+ params = mcp_types.ElicitRequestParams(message="Test elicitation message", requestedSchema={"type": "object"})
+
+ result = await host.handle_elicit_request(params)
+
+ assert isinstance(result, mcp_types.ErrorData)
+ assert result.code == mcp_types.INTERNAL_ERROR
+ assert "Elicitation request failed" in result.message
+
+
+async def test_mcp_session_host_list_roots_request() -> None:
+ """Test McpSessionHost handles list roots requests correctly."""
+ from pydantic import FileUrl
+
+ test_roots = [
+ mcp_types.Root(uri=FileUrl("file:///test1"), name="Test Root 1"),
+ mcp_types.Root(uri=FileUrl("file:///test2"), name="Test Root 2"),
+ ]
+
+ roots_provider = StaticRootsProvider(test_roots)
+ host = McpSessionHost(roots=roots_provider)
+
+ result = await host.handle_list_roots_request()
+
+ assert isinstance(result, mcp_types.ListRootsResult)
+ assert len(result.roots) == 2
+ assert str(result.roots[0].uri) == "file:///test1"
+ assert result.roots[0].name == "Test Root 1"
+ assert str(result.roots[1].uri) == "file:///test2"
+ assert result.roots[1].name == "Test Root 2"
+
+
+async def test_mcp_session_host_list_roots_request_callable() -> None:
+ """Test McpSessionHost handles list roots requests with callable roots."""
+ from pydantic import FileUrl
+
+ test_roots = [
+ mcp_types.Root(uri=FileUrl("file:///dynamic1"), name="Dynamic Root 1"),
+ mcp_types.Root(uri=FileUrl("file:///dynamic2"), name="Dynamic Root 2"),
+ ]
+
+ roots_provider = StaticRootsProvider(test_roots)
+ host = McpSessionHost(roots=roots_provider)
+
+ result = await host.handle_list_roots_request()
+
+ assert isinstance(result, mcp_types.ListRootsResult)
+ assert len(result.roots) == 2
+ assert str(result.roots[0].uri) == "file:///dynamic1"
+ assert result.roots[0].name == "Dynamic Root 1"
+
+
+async def test_mcp_session_host_list_roots_request_async_callable() -> None:
+ """Test McpSessionHost handles list roots requests with async callable roots (line 292)."""
+ from pydantic import FileUrl
+
+ test_roots = [
+ mcp_types.Root(uri=FileUrl("file:///async1"), name="Async Root 1"),
+ ]
+
+ roots_provider = StaticRootsProvider(test_roots)
+ host = McpSessionHost(roots=roots_provider)
+
+ result = await host.handle_list_roots_request()
+
+ assert isinstance(result, mcp_types.ListRootsResult)
+ assert len(result.roots) == 1
+ assert str(result.roots[0].uri) == "file:///async1"
+ assert result.roots[0].name == "Async Root 1"
+
+
+async def test_mcp_session_host_list_roots_request_no_roots() -> None:
+ """Test McpSessionHost returns error when no roots configured."""
+ host = McpSessionHost(roots=None)
+
+ result = await host.handle_list_roots_request()
+
+ assert isinstance(result, mcp_types.ErrorData)
+ assert result.code == mcp_types.INVALID_REQUEST
+ assert "Host does not support listing roots" in result.message
+
+
+async def test_mcp_session_host_list_roots_request_error_handling() -> None:
+ """Test McpSessionHost handles list roots errors correctly."""
+ # Create a mock roots provider that raises an exception
+ mock_roots_provider = MagicMock(spec=StaticRootsProvider)
+ mock_roots_provider.list_roots = AsyncMock(side_effect=Exception("Roots error"))
+
+ host = McpSessionHost(roots=mock_roots_provider)
+
+ result = await host.handle_list_roots_request()
+
+ assert isinstance(result, mcp_types.ErrorData)
+ assert result.code == mcp_types.INTERNAL_ERROR
+ assert "Caught error listing roots" in result.message
+
+
+# Configuration serialization tests removed due to API changes
+# The new implementation uses separate Sampler, RootsProvider, and Elicitor components
+# These tests would need significant rework to match the new architecture
+
+
+def test_mcp_session_host_initialization() -> None:
+ """Test McpSessionHost initialization."""
+ host = McpSessionHost()
+
+ assert host._sampler is None # type: ignore[reportPrivateUsage]
+ assert host._roots is None # type: ignore[reportPrivateUsage]
+ assert host._elicitor is None # type: ignore[reportPrivateUsage]
+
+
+async def test_mcp_session_host_with_vision_model(mock_model_client_with_vision: Any) -> None:
+ """Test McpSessionHost handles image content with vision-enabled model."""
+ sampler = ChatCompletionClientSampler(mock_model_client_with_vision)
+ host = McpSessionHost(sampler=sampler)
+
+ # Test with image content
+ image_content = mcp_types.ImageContent(
+ type="image",
+ data="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
+ mimeType="image/png",
+ )
+
+ params = mcp_types.CreateMessageRequestParams(
+ messages=[mcp_types.SamplingMessage(role="user", content=image_content)],
+ maxTokens=100,
+ )
+
+ result = await host.handle_sampling_request(params)
+
+ assert isinstance(result, mcp_types.CreateMessageResult)
+ assert result.role == "assistant"
+ mock_model_client_with_vision.create.assert_called_once()
+
+
+async def test_mcp_session_host_sampling_with_extra_args(mock_model_client: Any) -> None:
+ """Test McpSessionHost handles sampling requests with extra parameters."""
+ sampler = ChatCompletionClientSampler(mock_model_client)
+ host = McpSessionHost(sampler=sampler)
+
+ params = mcp_types.CreateMessageRequestParams(
+ messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
+ maxTokens=200,
+ temperature=0.7,
+ stopSequences=["STOP", "END"],
+ )
+
+ result = await host.handle_sampling_request(params)
+
+ assert isinstance(result, mcp_types.CreateMessageResult)
+ # Verify extra args were passed to model client
+ mock_model_client.create.assert_called_once()
+ call_args = mock_model_client.create.call_args[1]
+ extra_args = call_args["extra_create_args"]
+ assert extra_args["max_tokens"] == 200
+ assert extra_args["temperature"] == 0.7
+ assert extra_args["stop"] == ["STOP", "END"]
+
+
+async def test_mcp_session_host_sampling_with_complex_response(mock_model_client: Any) -> None:
+ """Test McpSessionHost handles complex/non-string model responses."""
+ # Configure model client to return complex content
+ mock_model_client.create = AsyncMock(
+ return_value=CreateResult(
+ content=[FunctionCall(id="test_func_call_1", name="test_func", arguments='{"param": "value"}')],
+ finish_reason="stop",
+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
+ cached=False,
+ )
+ )
+ sampler = ChatCompletionClientSampler(mock_model_client)
+ host = McpSessionHost(sampler=sampler)
+
+ params = mcp_types.CreateMessageRequestParams(
+ messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
+ maxTokens=100,
+ )
+
+ result = await host.handle_sampling_request(params)
+
+ assert isinstance(result, mcp_types.CreateMessageResult)
+ assert result.role == "assistant"
+ assert isinstance(result.content, mcp_types.TextContent)
+ # Should be JSON serialized version of complex content
+ assert "test_func" in result.content.text
+
+
+def mcp_server_params() -> StdioServerParams:
+ """Create server parameters that will launch the real MCP server subprocess."""
+ # Get the path to the simple MCP server
+ server_path = Path(__file__).parent.parent / "mcp_server_comprehensive.py"
+ return StdioServerParams(
+ command="uv",
+ args=["run", "python", str(server_path)],
+ read_timeout_seconds=10,
+ )
+
+
+# Integration test removed due to API changes - GroupChatAgentElicitor no longer exists
+# This test would need to be rewritten to use the new elicitor interfaces
+
+
+# Additional tests to improve coverage
+
+
+# StreamElicitor tests
+async def test_stream_elicitor_basic_functionality() -> None:
+ """Test StreamElicitor basic elicit functionality with schema."""
+ import io
+ from unittest.mock import patch
+
+ read_stream = io.StringIO("accept\n")
+ write_stream = io.StringIO()
+
+ elicitor = StreamElicitor(read_stream, write_stream)
+
+ schema = {"type": "object", "properties": {"response": {"type": "string"}}}
+ params = mcp_types.ElicitRequestParams(message="Test message", requestedSchema=schema)
+
+ # Mock asyncio.to_thread to return the read value synchronously
+ call_responses = ["accept\n", '{"response": "test"}\n'] # action then content for schema
+ call_count = {"count": 0}
+
+ def mock_return(*args: Any, **kwargs: Any) -> str:
+ result = call_responses[call_count["count"]]
+ call_count["count"] += 1
+ return result
+
+ with patch("asyncio.to_thread", side_effect=mock_return):
+ result = await elicitor.elicit(params)
+
+ assert isinstance(result, mcp_types.ElicitResult)
+ assert result.action == "accept"
+ assert result.content == {"response": "test"}
+
+ # Check that prompt was written
+ written_text = write_stream.getvalue()
+ assert "Test message" in written_text
+ assert "Choices:" in written_text
+ assert "[a]ccept" in written_text
+ assert "Input Schema:" in written_text
+
+
+async def test_stream_elicitor_initialization() -> None:
+ """Test StreamElicitor initialization and basic properties."""
+ import io
+
+ read_stream = io.StringIO()
+ write_stream = io.StringIO()
+ timeout = 5.0
+
+ elicitor = StreamElicitor(read_stream, write_stream, timeout)
+
+ assert elicitor._read_stream is read_stream # type: ignore[reportPrivateUsage]
+ assert elicitor._write_stream is write_stream # type: ignore[reportPrivateUsage]
+ assert elicitor._timeout == timeout # type: ignore[reportPrivateUsage]
+
+
+async def test_stream_elicitor_with_timeout() -> None:
+ """Test StreamElicitor with timeout functionality."""
+ import io
+ from unittest.mock import patch
+
+ read_stream = io.StringIO("decline\n")
+ write_stream = io.StringIO()
+
+ elicitor = StreamElicitor(read_stream, write_stream, timeout=5.0)
+
+ params = mcp_types.ElicitRequestParams(message="Test message", requestedSchema={})
+
+ call_responses = ["decline\n", "{}\n"] # action then content for schema
+ call_count = {"count": 0}
+
+ def mock_return(*args: Any, **kwargs: Any) -> str:
+ result = call_responses[call_count["count"]]
+ call_count["count"] += 1
+ return result
+
+ with (
+ patch("asyncio.to_thread", side_effect=mock_return),
+ patch("asyncio.wait_for", side_effect=mock_return) as mock_wait_for,
+ ):
+ result = await elicitor.elicit(params)
+
+ assert result.action == "decline"
+ # Verify wait_for was called with timeout (should be called twice - once for action, once for schema)
+ assert mock_wait_for.call_count >= 1
+
+
+async def test_stream_elicitor_with_schema() -> None:
+ """Test StreamElicitor with requestedSchema."""
+ import io
+ import json
+ from unittest.mock import patch
+
+ read_stream = io.StringIO("a\n")
+ write_stream = io.StringIO()
+
+ elicitor = StreamElicitor(read_stream, write_stream)
+
+ schema = {"type": "object", "properties": {"name": {"type": "string"}}}
+ params = mcp_types.ElicitRequestParams(message="Test message", requestedSchema=schema)
+
+ call_count = {"count": 0}
+
+ def side_effect(*args: Any, **kwargs: Any) -> str:
+ # First call returns action, second returns JSON content
+ if call_count["count"] == 0:
+ call_count["count"] += 1
+ return "a\n"
+ else:
+ return '{"name": "test"}\n'
+
+ with patch("asyncio.to_thread", side_effect=side_effect):
+ result = await elicitor.elicit(params)
+
+ assert result.action == "accept"
+ assert result.content == {"name": "test"}
+
+ # Check that schema was written
+ written_text = write_stream.getvalue()
+ assert "Input Schema:" in written_text
+ assert json.dumps(schema, indent=2) in written_text
+
+
+async def test_stream_elicitor_shorthand_mapping() -> None:
+ """Test StreamElicitor shorthand choice mapping."""
+ import io
+ from unittest.mock import patch
+
+ read_stream = io.StringIO("d\n") # Should map to "decline"
+ write_stream = io.StringIO()
+
+ elicitor = StreamElicitor(read_stream, write_stream)
+
+ params = mcp_types.ElicitRequestParams(message="Test", requestedSchema={})
+
+ call_responses = ["d\n", "{}\n"] # action then content for schema
+ call_count = {"count": 0}
+
+ def mock_return(*args: Any, **kwargs: Any) -> str:
+ result = call_responses[call_count["count"]]
+ call_count["count"] += 1
+ return result
+
+ with patch("asyncio.to_thread", side_effect=mock_return):
+ result = await elicitor.elicit(params)
+ assert result.action == "decline"
+
+
+# StdioElicitor tests
+def test_stdio_elicitor_initialization() -> None:
+ """Test StdioElicitor initialization."""
+ elicitor = StdioElicitor(timeout=10.0)
+
+ assert elicitor.timeout == 10.0
+ # Should use sys.stdin and sys.stdout
+ import sys
+
+ assert elicitor._read_stream is sys.stdin # type: ignore[reportPrivateUsage]
+ assert elicitor._write_stream is sys.stdout # type: ignore[reportPrivateUsage]
+
+
+def test_stdio_elicitor_config_serialization() -> None:
+ """Test StdioElicitor config serialization."""
+ elicitor = StdioElicitor(timeout=5.0)
+
+ config = elicitor.dump_component()
+
+ # Config should be a ComponentModel with nested config
+ assert config is not None
+ assert config.provider == "autogen_ext.tools.mcp.StdioElicitor"
+ assert config.component_type == "mcp_elicitor"
+ assert config.config["timeout"] == 5.0
+
+
+def test_stdio_elicitor_from_config() -> None:
+ """Test StdioElicitor load_component method."""
+ config_dict: dict[str, object] = {
+ "provider": "autogen_ext.tools.mcp.StdioElicitor",
+ "component_type": "mcp_elicitor",
+ "config": {"timeout": 15.0},
+ }
+ elicitor = StdioElicitor.load_component(config_dict)
+
+ assert isinstance(elicitor, StdioElicitor)
+ assert elicitor.timeout == 15.0
+
+
+# Additional sampling tests for missing coverage
+def test_parse_sampling_content_audio_unsupported() -> None:
+ """Test parse_sampling_content raises ValueError for audio content."""
+
+ audio_content = mcp_types.AudioContent(type="audio", data="audio_data", mimeType="audio/wav")
+
+ with pytest.raises(ValueError, match="Unsupported content type: audio"):
+ parse_sampling_content(audio_content)
+
+
+def test_parse_sampling_content_image_without_vision() -> None:
+ """Test parse_sampling_content raises RuntimeError for image without vision model."""
+
+ image_content = mcp_types.ImageContent(
+ type="image",
+ data="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
+ mimeType="image/png",
+ )
+
+ model_info: ModelInfo = {
+ "vision": False,
+ "function_calling": False,
+ "json_output": False,
+ "family": "test-model",
+ "structured_output": False,
+ }
+
+ with pytest.raises(RuntimeError, match="model test-model does not support vision"):
+ parse_sampling_content(image_content, model_info)
+
+
+def test_parse_sampling_message_user_with_image() -> None:
+ """Test parse_sampling_message with user message containing image."""
+ from autogen_ext.tools.mcp._host._sampling import parse_sampling_message
+
+ image_content = mcp_types.ImageContent(
+ type="image",
+ data="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
+ mimeType="image/png",
+ )
+
+ message = mcp_types.SamplingMessage(role="user", content=image_content)
+
+ model_info: ModelInfo = {
+ "vision": True,
+ "function_calling": False,
+ "json_output": False,
+ "family": "vision-model",
+ "structured_output": False,
+ }
+
+ result = parse_sampling_message(message, model_info)
+
+ assert isinstance(result, UserMessage)
+ assert len(result.content) == 1
+ # Should be an Image object
+ from autogen_core import Image
+
+ assert isinstance(result.content[0], Image)
+
+
+def test_parse_sampling_message_invalid_role() -> None:
+ """Test parse_sampling_message raises ValueError for invalid role."""
+ from autogen_ext.tools.mcp._host._sampling import parse_sampling_message
+
+ # Create a mock message object that bypasses Pydantic validation
+ class MockMessage:
+ def __init__(self, role: str, content: Any):
+ self.role = role
+ self.content = content
+
+ text_content = mcp_types.TextContent(type="text", text="Hello")
+ message = MockMessage(role="invalid", content=text_content)
+
+ with pytest.raises(ValueError, match="Unrecognized message role: invalid"):
+ parse_sampling_message(message) # type: ignore[arg-type]
+
+
+# Additional roots provider tests
+def test_static_roots_provider_config_serialization() -> None:
+ """Test StaticRootsProvider config serialization."""
+ from pydantic import FileUrl
+
+ test_roots = [
+ mcp_types.Root(uri=FileUrl("file:///test"), name="Test Root"),
+ ]
+
+ provider = StaticRootsProvider(test_roots)
+ config = provider.dump_component()
+
+ # Config should be a ComponentModel with nested config
+ assert config is not None
+ assert config.provider == "autogen_ext.tools.mcp.StaticRootsProvider"
+ assert config.component_type == "mcp_roots_provider"
+ assert len(config.config["roots"]) == 1
+
+
+def test_static_roots_provider_from_config() -> None:
+ """Test StaticRootsProvider load_component method."""
+ from pydantic import FileUrl
+
+ test_roots = [
+ mcp_types.Root(uri=FileUrl("file:///config_test"), name="Config Root"),
+ ]
+
+ # Create a proper ComponentModel-style config
+ component_config: dict[str, object] = {
+ "provider": "autogen_ext.tools.mcp.StaticRootsProvider",
+ "component_type": "mcp_roots_provider",
+ "config": {"roots": test_roots},
+ }
+ provider = StaticRootsProvider.load_component(component_config)
+
+ assert isinstance(provider, StaticRootsProvider)
+
+
+# ChatCompletionClientSampler config tests
+def test_chat_completion_client_sampler_config_serialization(mock_model_client: Any) -> None:
+ """Test ChatCompletionClientSampler config serialization."""
+ mock_model_client.dump_component = MagicMock(return_value={"type": "mock", "config": {}})
+
+ sampler = ChatCompletionClientSampler(mock_model_client)
+ config = sampler.dump_component()
+
+ # Config should be a ComponentModel with nested config
+ assert config is not None
+ assert config.provider == "autogen_ext.tools.mcp.ChatCompletionClientSampler"
+ assert config.component_type == "mcp_sampler"
+ assert config.config["client_config"] == {"type": "mock", "config": {}}
+
+
+def test_chat_completion_client_sampler_from_config() -> None:
+ """Test ChatCompletionClientSampler load_component method."""
+ from autogen_core.models import ChatCompletionClient
+
+ # Create a proper ComponentModel-style config
+ component_config: dict[str, object] = {
+ "provider": "autogen_ext.tools.mcp.ChatCompletionClientSampler",
+ "component_type": "mcp_sampler",
+ "config": {"client_config": {"type": "mock", "config": {}}},
+ }
+
+ mock_client = MagicMock()
+ with patch.object(ChatCompletionClient, "load_component", return_value=mock_client):
+ sampler = ChatCompletionClientSampler.load_component(component_config)
+
+ assert isinstance(sampler, ChatCompletionClientSampler)
+
+
+# Additional McpSessionHost tests to improve coverage
+def test_mcp_session_host_component_attributes() -> None:
+ """Test McpSessionHost component configuration attributes (lines 99-101)."""
+ from autogen_ext.tools.mcp._host._session_host import McpSessionHostConfig
+
+ assert McpSessionHost.component_type == "mcp_session_host"
+ assert McpSessionHost.component_config_schema == McpSessionHostConfig
+ assert McpSessionHost.component_provider_override == "autogen_ext.tools.mcp.McpSessionHost"
+
+
+def test_mcp_session_host_constructor_attributes() -> None:
+ """Test McpSessionHost constructor sets attributes correctly (lines 116-118)."""
+ mock_sampler = MagicMock()
+ mock_roots = MagicMock()
+ mock_elicitor = MagicMock()
+
+ host = McpSessionHost(
+ sampler=mock_sampler,
+ roots=mock_roots,
+ elicitor=mock_elicitor,
+ )
+
+ assert host._sampler is mock_sampler # type: ignore[reportPrivateUsage]
+ assert host._roots is mock_roots # type: ignore[reportPrivateUsage]
+ assert host._elicitor is mock_elicitor # type: ignore[reportPrivateUsage]
+
+
+def test_mcp_session_host_to_config_full() -> None:
+ """Test McpSessionHost _to_config method with all components (lines 194-198)."""
+ from autogen_ext.tools.mcp._host._session_host import McpSessionHostConfig
+
+ # Create mock components with dump_component methods
+ mock_sampler = MagicMock()
+ mock_sampler.dump_component = MagicMock(return_value={"type": "sampler", "config": {}})
+
+ mock_roots = MagicMock()
+ mock_roots.dump_component = MagicMock(return_value={"type": "roots", "config": {}})
+
+ mock_elicitor = MagicMock()
+ mock_elicitor.dump_component = MagicMock(return_value={"type": "elicitor", "config": {}})
+
+ host = McpSessionHost(
+ sampler=mock_sampler,
+ roots=mock_roots,
+ elicitor=mock_elicitor,
+ )
+
+ config = host._to_config() # type: ignore[reportPrivateUsage]
+
+ assert isinstance(config, McpSessionHostConfig)
+ assert config.sampler == {"type": "sampler", "config": {}}
+ assert config.elicitor == {"type": "elicitor", "config": {}}
+ assert config.roots == {"type": "roots", "config": {}}
+
+
+def test_mcp_session_host_to_config_partial() -> None:
+ """Test McpSessionHost _to_config method with some None components."""
+ from autogen_ext.tools.mcp._host._session_host import McpSessionHostConfig
+
+ mock_sampler = MagicMock()
+ mock_sampler.dump_component = MagicMock(return_value={"type": "sampler", "config": {}})
+
+ host = McpSessionHost(sampler=mock_sampler, roots=None, elicitor=None)
+
+ config = host._to_config() # type: ignore[reportPrivateUsage]
+
+ assert isinstance(config, McpSessionHostConfig)
+ assert config.sampler == {"type": "sampler", "config": {}}
+ assert config.elicitor is None
+ assert config.roots is None
+
+
+def test_mcp_session_host_from_config() -> None:
+ """Test McpSessionHost _from_config method (lines 201-204)."""
+ from autogen_ext.tools.mcp import Elicitor, RootsProvider, Sampler
+ from autogen_ext.tools.mcp._host._session_host import McpSessionHostConfig
+
+ # Create mock components
+ mock_sampler = MagicMock()
+ mock_elicitor = MagicMock()
+ mock_roots = MagicMock()
+
+ sampler_config: dict[str, object] = {"type": "mock_sampler", "config": {}}
+ elicitor_config: dict[str, object] = {"type": "mock_elicitor", "config": {}}
+ roots_config: dict[str, object] = {"type": "mock_roots", "config": {}}
+
+ config = McpSessionHostConfig(
+ sampler=sampler_config,
+ elicitor=elicitor_config,
+ roots=roots_config,
+ )
+
+ # Mock the load_component methods
+ with (
+ patch.object(Sampler, "load_component", return_value=mock_sampler),
+ patch.object(Elicitor, "load_component", return_value=mock_elicitor),
+ patch.object(RootsProvider, "load_component", return_value=mock_roots),
+ ):
+ host = McpSessionHost._from_config(config) # type: ignore[reportPrivateUsage]
+
+ assert host._sampler is mock_sampler # type: ignore[reportPrivateUsage]
+ assert host._elicitor is mock_elicitor # type: ignore[reportPrivateUsage]
+ assert host._roots is mock_roots # type: ignore[reportPrivateUsage]
+
+
+def test_mcp_session_host_from_config_with_nones() -> None:
+ """Test McpSessionHost _from_config method with None components."""
+ from autogen_ext.tools.mcp._host._session_host import McpSessionHostConfig
+
+ config = McpSessionHostConfig(sampler=None, elicitor=None, roots=None)
+
+ host = McpSessionHost._from_config(config) # type: ignore[reportPrivateUsage]
+
+ assert host._sampler is None # type: ignore[reportPrivateUsage]
+ assert host._elicitor is None # type: ignore[reportPrivateUsage]
+ assert host._roots is None # type: ignore[reportPrivateUsage]
+
+
+async def test_mcp_session_host_sampling_with_sampler_exception() -> None:
+ """Test McpSessionHost handles sampler exceptions (lines 143-147)."""
+ mock_sampler = MagicMock()
+ mock_sampler.sample = AsyncMock(side_effect=RuntimeError("Sampler failed"))
+
+ host = McpSessionHost(sampler=mock_sampler)
+
+ params = mcp_types.CreateMessageRequestParams(
+ messages=[mcp_types.SamplingMessage(role="user", content=mcp_types.TextContent(type="text", text="Hello"))],
+ maxTokens=100,
+ )
+
+ result = await host.handle_sampling_request(params)
+
+ assert isinstance(result, mcp_types.ErrorData)
+ assert result.code == mcp_types.INTERNAL_ERROR
+ assert "Sampling request failed" in result.message
+ assert "Sampler failed" in result.message
+
+
+async def test_mcp_session_host_elicit_with_elicitor_exception() -> None:
+ """Test McpSessionHost handles elicitor exceptions (lines 169-172)."""
+ mock_elicitor = MagicMock()
+ mock_elicitor.elicit = AsyncMock(side_effect=ValueError("Elicitor failed"))
+
+ host = McpSessionHost(elicitor=mock_elicitor)
+
+ params = mcp_types.ElicitRequestParams(message="Test", requestedSchema={})
+
+ result = await host.handle_elicit_request(params)
+
+ assert isinstance(result, mcp_types.ErrorData)
+ assert result.code == mcp_types.INTERNAL_ERROR
+ assert "Elicitation request failed" in result.message
+ assert "Elicitor failed" in result.message
diff --git a/python/packages/autogen-ext/tests/tools/test_mcp_workbench_model_client.py b/python/packages/autogen-ext/tests/tools/test_mcp_workbench_model_client.py
deleted file mode 100644
index fe6567bf7..000000000
--- a/python/packages/autogen-ext/tests/tools/test_mcp_workbench_model_client.py
+++ /dev/null
@@ -1,831 +0,0 @@
-import asyncio
-from typing import Any, AsyncGenerator, Sequence
-from unittest.mock import AsyncMock, MagicMock
-
-import pytest
-from autogen_core import Component
-from autogen_core.models import (
- ChatCompletionClient,
- CreateResult,
- LLMMessage,
- ModelInfo,
- RequestUsage,
-)
-from autogen_core.tools import Tool, ToolSchema
-from autogen_ext.tools.mcp import McpWorkbench, StdioServerParams
-from mcp.types import CallToolResult, ListToolsResult, TextContent
-from mcp.types import Tool as McpTool
-from pydantic import BaseModel
-
-
-class MockChatCompletionClientConfig(BaseModel):
- model_info: ModelInfo
-
-
-class MockChatCompletionClient(ChatCompletionClient, Component[MockChatCompletionClientConfig]):
- """Mock chat completion client for testing."""
-
- component_type = "test"
- component_config_schema = MockChatCompletionClientConfig
- component_provider_override = f"{__module__}.MockChatCompletionClient"
-
- def __init__(self, model_info: ModelInfo | None = None):
- self._model_info = model_info or {
- "vision": False,
- "function_calling": False,
- "json_output": False,
- "family": "test-model",
- "structured_output": False,
- }
-
- @property
- def model_info(self) -> ModelInfo:
- return self._model_info
-
- async def create(self, *args: Any, **kwargs: Any) -> CreateResult:
- return CreateResult(
- content="Mock response",
- finish_reason="stop",
- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
- cached=False,
- )
-
- def create_stream(self, *args: Any, **kwargs: Any) -> AsyncGenerator[str | CreateResult, None]:
- async def mock_stream() -> AsyncGenerator[str | CreateResult, None]:
- yield "Mock streaming response"
- yield CreateResult(
- content="Mock response",
- finish_reason="stop",
- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
- cached=False,
- )
-
- return mock_stream()
-
- async def close(self) -> None:
- pass
-
- def actual_usage(self) -> RequestUsage:
- return RequestUsage(prompt_tokens=0, completion_tokens=0)
-
- def total_usage(self) -> RequestUsage:
- return RequestUsage(prompt_tokens=0, completion_tokens=0)
-
- def count_tokens(self, messages: Sequence[LLMMessage], *, tools: Sequence[Tool | ToolSchema] = []) -> int:
- return 10
-
- def remaining_tokens(self, messages: Sequence[LLMMessage], *, tools: Sequence[Tool | ToolSchema] = []) -> int:
- return 1000
-
- @property
- def capabilities(self) -> Any: # ModelCapabilities is deprecated
- return {}
-
- def _to_config(self) -> BaseModel:
- return MockChatCompletionClientConfig(model_info=self.model_info)
-
- @classmethod
- def _from_config(cls, config: MockChatCompletionClientConfig) -> "MockChatCompletionClient":
- return cls(config.model_info)
-
-
-def sample_mcp_tools() -> list[McpTool]:
- """Create sample MCP tools for testing."""
- return [
- McpTool(
- name="test_tool",
- description="A test tool",
- inputSchema={
- "type": "object",
- "properties": {"param": {"type": "string"}},
- "required": ["param"],
- },
- ),
- ]
-
-
-def mock_mcp_actor() -> AsyncMock:
- """Mock MCP session actor."""
- actor = AsyncMock()
- return actor
-
-
-def sample_server_params() -> StdioServerParams:
- """Sample server parameters for testing."""
- return StdioServerParams(command="echo", args=["test"])
-
-
-def mock_model_client() -> MockChatCompletionClient:
- """Mock model client for testing."""
- model_client = MockChatCompletionClient()
- # Set up the mock's create method
- mock_create = AsyncMock(
- return_value=CreateResult(
- content="Mock response",
- finish_reason="stop",
- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
- cached=False,
- )
- )
- model_client.create = mock_create # type: ignore[method-assign]
- return model_client
-
-
-def mock_model_client_with_vision() -> MockChatCompletionClient:
- """Mock model client with vision support for testing."""
- model_client = MockChatCompletionClient(
- model_info={
- "vision": True,
- "function_calling": False,
- "json_output": False,
- "family": "test-vision-model",
- "structured_output": False,
- }
- )
- # Set up the mock's create method
- mock_create = AsyncMock(
- return_value=CreateResult(
- content="Mock response",
- finish_reason="stop",
- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
- cached=False,
- )
- )
- model_client.create = mock_create # type: ignore[method-assign]
- return model_client
-
-
-async def test_mcp_workbench_with_model_client_initialization(
- sample_server_params: StdioServerParams,
- mock_model_client: MockChatCompletionClient,
-) -> None:
- """Test McpWorkbench initialization with a model client."""
- workbench = McpWorkbench(
- server_params=sample_server_params,
- model_client=mock_model_client,
- )
-
- assert workbench._model_client is mock_model_client # type: ignore[attr-defined]
-
- # Test that the workbench is properly configured
- config = workbench._to_config() # type: ignore[attr-defined]
- assert config.model_client is not None
- assert config.server_params == sample_server_params
-
-
-async def test_mcp_workbench_without_model_client_initialization(
- sample_server_params: StdioServerParams,
-) -> None:
- """Test McpWorkbench initialization without a model client."""
- workbench = McpWorkbench(server_params=sample_server_params)
-
- assert workbench._model_client is None # type: ignore[attr-defined]
-
- # Test that the workbench is properly configured
- config = workbench._to_config() # type: ignore[attr-defined]
- assert config.model_client is None
- assert config.server_params == sample_server_params
-
-
-async def test_mcp_workbench_serialization_with_model_client(
- sample_server_params: StdioServerParams,
- mock_model_client: MockChatCompletionClient,
-) -> None:
- """Test serialization and deserialization of McpWorkbench with model client."""
- # Create original workbench
- original_workbench = McpWorkbench(
- server_params=sample_server_params,
- model_client=mock_model_client,
- )
-
- # Serialize to config
- config = original_workbench._to_config() # type: ignore[attr-defined]
- assert config.model_client is not None
-
- # Deserialize from config
- loaded_workbench = McpWorkbench._from_config(config) # type: ignore[attr-defined]
-
- # Verify the loaded workbench
- assert loaded_workbench.server_params == sample_server_params
- assert loaded_workbench._model_client is not None # type: ignore[attr-defined]
- assert loaded_workbench._model_client.model_info == mock_model_client.model_info # type: ignore[attr-defined]
-
-
-async def test_mcp_workbench_serialization_without_model_client(
- sample_server_params: StdioServerParams,
-) -> None:
- """Test serialization and deserialization of McpWorkbench without model client."""
- # Create original workbench
- original_workbench = McpWorkbench(server_params=sample_server_params)
-
- # Serialize to config
- config = original_workbench._to_config() # type: ignore[attr-defined]
- assert config.model_client is None
-
- # Deserialize from config
- loaded_workbench = McpWorkbench._from_config(config) # type: ignore[attr-defined]
-
- # Verify the loaded workbench
- assert loaded_workbench.server_params == sample_server_params
- assert loaded_workbench._model_client is None # type: ignore[attr-defined]
-
-
-async def test_mcp_workbench_model_client_passed_to_actor(
- sample_mcp_tools: list[McpTool],
- mock_mcp_actor: AsyncMock,
- sample_server_params: StdioServerParams,
- mock_model_client: MockChatCompletionClient,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Test that model client is properly passed to the MCP actor."""
- # Mock the McpSessionActor creation
- mock_actor_class = MagicMock()
- mock_actor_instance = mock_mcp_actor
- mock_actor_class.return_value = mock_actor_instance
-
- monkeypatch.setattr("autogen_ext.tools.mcp._workbench.McpSessionActor", mock_actor_class)
-
- # Create workbench with model client
- workbench = McpWorkbench(
- server_params=sample_server_params,
- model_client=mock_model_client,
- )
-
- # Mock list_tools response
- list_tools_result = ListToolsResult(tools=sample_mcp_tools)
- future_result: asyncio.Future[ListToolsResult] = asyncio.Future()
- future_result.set_result(list_tools_result)
- mock_mcp_actor.call.return_value = future_result
-
- try:
- # Start the workbench - this should create the actor with the model client
- await workbench.start()
-
- # Verify that the actor was created with the model client
- mock_actor_class.assert_called_once_with(sample_server_params, model_client=mock_model_client)
-
- # Verify that initialize was called on the actor
- mock_mcp_actor.initialize.assert_called_once()
-
- finally:
- if workbench._actor: # type: ignore[attr-defined]
- workbench._actor = None # type: ignore[attr-defined]
-
-
-async def test_mcp_workbench_start_without_explicit_model_client(
- sample_mcp_tools: list[McpTool],
- mock_mcp_actor: AsyncMock,
- sample_server_params: StdioServerParams,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Test that actor is created correctly when no model client is provided."""
- # Mock the McpSessionActor creation
- mock_actor_class = MagicMock()
- mock_actor_instance = mock_mcp_actor
- mock_actor_class.return_value = mock_actor_instance
-
- monkeypatch.setattr("autogen_ext.tools.mcp._workbench.McpSessionActor", mock_actor_class)
-
- # Create workbench without model client
- workbench = McpWorkbench(server_params=sample_server_params)
-
- # Mock list_tools response
- list_tools_result = ListToolsResult(tools=sample_mcp_tools)
- future_result: asyncio.Future[ListToolsResult] = asyncio.Future()
- future_result.set_result(list_tools_result)
- mock_mcp_actor.call.return_value = future_result
-
- try:
- # Start the workbench - this should create the actor without model client
- await workbench.start()
-
- # Verify that the actor was created without the model client
- mock_actor_class.assert_called_once_with(sample_server_params, model_client=None)
-
- # Verify that initialize was called on the actor
- mock_mcp_actor.initialize.assert_called_once()
-
- finally:
- if workbench._actor: # type: ignore[attr-defined]
- workbench._actor = None # type: ignore[attr-defined]
-
-
-async def test_mcp_workbench_list_tools_with_model_client(
- sample_mcp_tools: list[McpTool],
- mock_mcp_actor: AsyncMock,
- sample_server_params: StdioServerParams,
- mock_model_client: MockChatCompletionClient,
-) -> None:
- """Test that list_tools works correctly with model client."""
- # Create workbench with model client
- workbench = McpWorkbench(
- server_params=sample_server_params,
- model_client=mock_model_client,
- )
- workbench._actor = mock_mcp_actor # type: ignore[attr-defined]
-
- # Mock list_tools response
- list_tools_result = ListToolsResult(tools=sample_mcp_tools)
- future_result: asyncio.Future[ListToolsResult] = asyncio.Future()
- future_result.set_result(list_tools_result)
- mock_mcp_actor.call.return_value = future_result
-
- try:
- # List tools
- tools = await workbench.list_tools()
-
- # Verify tools are returned correctly
- assert len(tools) == 1
- assert tools[0]["name"] == "test_tool"
- assert tools[0].get("description") == "A test tool"
-
- # Verify actor was called correctly
- mock_mcp_actor.call.assert_called_with("list_tools", None)
-
- finally:
- workbench._actor = None # type: ignore[attr-defined]
-
-
-async def test_mcp_workbench_call_tool_with_model_client(
- mock_mcp_actor: AsyncMock,
- sample_server_params: StdioServerParams,
- mock_model_client: MockChatCompletionClient,
-) -> None:
- """Test that call_tool works correctly with model client."""
- # Create workbench with model client
- workbench = McpWorkbench(
- server_params=sample_server_params,
- model_client=mock_model_client,
- )
- workbench._actor = mock_mcp_actor # type: ignore[attr-defined]
-
- # Mock call_tool response
- call_tool_result = CallToolResult(
- content=[TextContent(type="text", text="Tool executed successfully")],
- isError=False,
- )
- future_result: asyncio.Future[CallToolResult] = asyncio.Future()
- future_result.set_result(call_tool_result)
- mock_mcp_actor.call.return_value = future_result
-
- try:
- # Call tool
- result = await workbench.call_tool(
- name="test_tool",
- arguments={"param": "test_value"},
- )
-
- # Verify result
- assert not result.is_error
- assert len(result.result) == 1
- assert result.result[0].content == "Tool executed successfully"
-
- # Verify actor was called correctly
- mock_mcp_actor.call.assert_called_with("call_tool", {"name": "test_tool", "kargs": {"param": "test_value"}})
-
- finally:
- workbench._actor = None # type: ignore[attr-defined]
-
-
-async def test_mcp_workbench_state_operations_with_model_client(
- sample_server_params: StdioServerParams,
- mock_model_client: MockChatCompletionClient,
-) -> None:
- """Test state save/load operations with model client."""
- # Create workbench with model client
- workbench = McpWorkbench(
- server_params=sample_server_params,
- model_client=mock_model_client,
- )
-
- # Save state
- state = await workbench.save_state()
- assert state["type"] == "McpWorkBenchState"
-
- # Load state (should not affect model client)
- await workbench.load_state(state)
-
- # Model client should still be there
- assert workbench._model_client is mock_model_client # type: ignore[attr-defined]
-
-
-async def test_mcp_workbench_fallback_start_behavior(
- sample_mcp_tools: list[McpTool],
- mock_mcp_actor: AsyncMock,
- sample_server_params: StdioServerParams,
- mock_model_client: MockChatCompletionClient,
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Test fallback start behavior when actor is not initialized."""
- # Mock the McpSessionActor creation
- mock_actor_class = MagicMock()
- mock_actor_instance = mock_mcp_actor
- mock_actor_class.return_value = mock_actor_instance
-
- monkeypatch.setattr("autogen_ext.tools.mcp._workbench.McpSessionActor", mock_actor_class)
-
- # Create workbench with model client
- workbench = McpWorkbench(
- server_params=sample_server_params,
- model_client=mock_model_client,
- )
-
- # Ensure actor is not initialized
- assert workbench._actor is None # type: ignore[attr-defined]
-
- # Mock list_tools response
- list_tools_result = ListToolsResult(tools=sample_mcp_tools)
- future_result: asyncio.Future[ListToolsResult] = asyncio.Future()
- future_result.set_result(list_tools_result)
- mock_mcp_actor.call.return_value = future_result
-
- try:
- # Call list_tools without explicitly starting - should auto-start
- tools = await workbench.list_tools()
-
- # Verify that the actor was created with the model client
- mock_actor_class.assert_called_once_with(sample_server_params, model_client=mock_model_client)
-
- # Verify that initialize was called on the actor
- mock_mcp_actor.initialize.assert_called_once()
-
- # Verify tools are returned correctly
- assert len(tools) == 1
- assert tools[0]["name"] == "test_tool"
-
- finally:
- if workbench._actor: # type: ignore[attr-defined]
- workbench._actor = None # type: ignore[attr-defined]
-
-
-async def test_mcp_workbench_model_client_vision_support(
- sample_server_params: StdioServerParams,
- mock_model_client_with_vision: MockChatCompletionClient,
-) -> None:
- """Test that model client with vision support is properly configured."""
- # Create workbench with vision-enabled model client
- workbench = McpWorkbench(
- server_params=sample_server_params,
- model_client=mock_model_client_with_vision,
- )
-
- # Verify model client has vision capabilities
- assert workbench._model_client is not None # type: ignore[attr-defined]
- assert workbench._model_client.model_info["vision"] is True # type: ignore[attr-defined]
- assert workbench._model_client.model_info["family"] == "test-vision-model" # type: ignore[attr-defined]
-
- # Test serialization preserves vision capabilities
- config = workbench._to_config() # type: ignore[attr-defined]
- loaded_workbench = McpWorkbench._from_config(config) # type: ignore[attr-defined]
-
- assert loaded_workbench._model_client is not None # type: ignore[attr-defined]
- assert loaded_workbench._model_client.model_info["vision"] is True # type: ignore[attr-defined]
- assert loaded_workbench._model_client.model_info["family"] == "test-vision-model" # type: ignore[attr-defined]
-
-
-async def test_mcp_workbench_component_interface(
- sample_server_params: StdioServerParams,
- mock_model_client: MockChatCompletionClient,
-) -> None:
- """Test that McpWorkbench properly implements the Component interface."""
- # Test component provider override
- assert McpWorkbench.component_provider_override == "autogen_ext.tools.mcp.McpWorkbench"
-
- # Test config schema
- config_schema = McpWorkbench.component_config_schema
- assert config_schema is not None
-
- # Test serialization/deserialization through component interface
- workbench = McpWorkbench(
- server_params=sample_server_params,
- model_client=mock_model_client,
- )
-
- # Test _to_config
- config = workbench._to_config() # type: ignore[attr-defined]
- assert hasattr(config, "server_params")
- assert hasattr(config, "model_client")
- assert hasattr(config, "tool_overrides")
-
- # Test _from_config
- loaded_workbench = McpWorkbench._from_config(config) # type: ignore[attr-defined]
- assert loaded_workbench.server_params == sample_server_params
- assert loaded_workbench._model_client is not None # type: ignore[attr-defined]
-
-
-async def test_sampling_callback_invocation(
- mock_model_client: MockChatCompletionClient, sample_server_params: StdioServerParams
-) -> None:
- """Test that the sampling_callback in McpSessionActor is actually called when requested."""
- from unittest.mock import MagicMock
-
- from autogen_ext.tools.mcp._actor import McpSessionActor
- from mcp.shared.context import RequestContext
- from mcp.types import CreateMessageRequestParams, CreateMessageResult, SamplingMessage, TextContent
-
- # Set up the mock for this specific test
- mock_create = AsyncMock(
- return_value=CreateResult(
- content="Mock response",
- finish_reason="stop",
- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
- cached=False,
- )
- )
- mock_model_client.create = mock_create # type: ignore[method-assign]
-
- # Create an actor with a model client
- actor = McpSessionActor(sample_server_params, model_client=mock_model_client)
-
- # Create mock request context and parameters for sampling
- mock_context = MagicMock(spec=RequestContext)
- sample_params = CreateMessageRequestParams(
- messages=[SamplingMessage(role="user", content=TextContent(type="text", text="Hello, how are you?"))],
- maxTokens=100,
- )
-
- # Test the sampling callback directly
- result = await actor._sampling_callback(mock_context, sample_params) # type: ignore[attr-defined]
-
- # Verify the result is a CreateMessageResult (not an error)
- assert isinstance(result, CreateMessageResult)
- assert result.role == "assistant"
- assert result.content.type == "text"
- assert result.content.text == "Mock response"
- assert result.model == "test-model"
- assert result.stopReason == "stop"
-
- # Verify the model client was called correctly
- assert mock_create.called
- # Get the call arguments
- call_args = mock_create.call_args
- messages = call_args.kwargs["messages"] # Messages are passed as keyword argument
- assert len(messages) == 1
- assert messages[0].source == "user"
- assert "Hello, how are you?" in str(messages[0].content)
-
-
-async def test_sampling_callback_without_model_client(sample_server_params: StdioServerParams) -> None:
- """Test that sampling_callback returns error when no model client is provided."""
- from unittest.mock import MagicMock
-
- from autogen_ext.tools.mcp._actor import McpSessionActor
- from mcp.shared.context import RequestContext
- from mcp.types import CreateMessageRequestParams, ErrorData, SamplingMessage, TextContent
-
- # Create an actor without a model client
- actor = McpSessionActor(sample_server_params, model_client=None)
-
- # Create mock request context and parameters
- mock_context = MagicMock(spec=RequestContext)
- sample_params = CreateMessageRequestParams(
- messages=[SamplingMessage(role="user", content=TextContent(type="text", text="Hello, how are you?"))],
- maxTokens=100,
- )
-
- # Test the sampling callback
- result = await actor._sampling_callback(mock_context, sample_params) # type: ignore[attr-defined]
-
- # Verify the result is an ErrorData (indicating no model client)
- assert isinstance(result, ErrorData)
-
-
-async def test_sampling_callback_with_system_prompt(
- mock_model_client: MockChatCompletionClient, sample_server_params: StdioServerParams
-) -> None:
- """Test sampling_callback with system prompt."""
- from unittest.mock import MagicMock
-
- from autogen_ext.tools.mcp._actor import McpSessionActor
- from mcp.shared.context import RequestContext
- from mcp.types import CreateMessageRequestParams, CreateMessageResult, SamplingMessage, TextContent
-
- # Set up the mock for this specific test
- mock_create = AsyncMock(
- return_value=CreateResult(
- content="Mock response",
- finish_reason="stop",
- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
- cached=False,
- )
- )
- mock_model_client.create = mock_create # type: ignore[method-assign]
-
- # Create an actor with a model client
- actor = McpSessionActor(sample_server_params, model_client=mock_model_client)
-
- # Create mock request context and parameters with system prompt
- mock_context = MagicMock(spec=RequestContext)
- sample_params = CreateMessageRequestParams(
- messages=[SamplingMessage(role="user", content=TextContent(type="text", text="What's the weather?"))],
- systemPrompt="You are a helpful weather assistant.",
- maxTokens=100,
- )
-
- # Test the sampling callback
- result = await actor._sampling_callback(mock_context, sample_params) # type: ignore[attr-defined]
-
- # Verify the result
- assert isinstance(result, CreateMessageResult)
-
- # Verify the model client was called with system prompt
- assert mock_create.called
- call_args = mock_create.call_args
- messages = call_args.kwargs["messages"]
- assert len(messages) == 2 # system + user message
-
- # Check system message
- system_msg = messages[0]
- assert system_msg.__class__.__name__ == "SystemMessage"
- assert "helpful weather assistant" in str(system_msg.content)
-
- # Check user message
- user_msg = messages[1]
- assert user_msg.source == "user"
- assert "weather" in str(user_msg.content)
-
-
-async def test_sampling_callback_with_image_content(
- mock_model_client_with_vision: MockChatCompletionClient, sample_server_params: StdioServerParams
-) -> None:
- """Test sampling_callback with image content when vision is supported."""
- from unittest.mock import MagicMock
-
- from autogen_ext.tools.mcp._actor import McpSessionActor
- from mcp.shared.context import RequestContext
- from mcp.types import CreateMessageRequestParams, CreateMessageResult, ImageContent, SamplingMessage
-
- # Set up the mock for this specific test
- mock_create = AsyncMock(
- return_value=CreateResult(
- content="Mock response",
- finish_reason="stop",
- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),
- cached=False,
- )
- )
- mock_model_client_with_vision.create = mock_create # type: ignore[method-assign]
-
- # Create an actor with a vision-capable model client
- actor = McpSessionActor(sample_server_params, model_client=mock_model_client_with_vision)
-
- # Create a simple test image (1x1 pixel PNG) - using a proper PNG
- # This is a valid 1x1 transparent PNG
- test_image_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
-
- # Create mock request context and parameters with image
- mock_context = MagicMock(spec=RequestContext)
- sample_params = CreateMessageRequestParams(
- messages=[
- SamplingMessage(role="user", content=ImageContent(type="image", data=test_image_b64, mimeType="image/png"))
- ],
- maxTokens=100,
- )
-
- # Test the sampling callback
- result = await actor._sampling_callback(mock_context, sample_params) # type: ignore[attr-defined]
-
- # Verify the result
- assert isinstance(result, CreateMessageResult)
-
- # Verify the model client was called
- assert mock_create.called
- call_args = mock_create.call_args
- messages = call_args.kwargs["messages"]
- assert len(messages) == 1
-
- # Check that the message contains image content
- user_msg = messages[0]
- assert user_msg.source == "user"
- # The content should be a list containing an Image object
- assert isinstance(user_msg.content, list)
- assert len(user_msg.content) == 1 # type: ignore[arg-type]
-
-
-async def test_sampling_callback_image_without_vision_support(
- mock_model_client: MockChatCompletionClient, sample_server_params: StdioServerParams
-) -> None:
- """Test sampling_callback fails gracefully when image is sent to non-vision model."""
- from unittest.mock import MagicMock
-
- from autogen_ext.tools.mcp._actor import McpSessionActor
- from mcp.shared.context import RequestContext
- from mcp.types import CreateMessageRequestParams, ErrorData, ImageContent, SamplingMessage
-
- # Create an actor with a non-vision model client
- actor = McpSessionActor(sample_server_params, model_client=mock_model_client)
-
- # Create a simple test image - using the same valid PNG
- test_image_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
-
- # Create mock request context and parameters with image
- mock_context = MagicMock(spec=RequestContext)
- sample_params = CreateMessageRequestParams(
- messages=[
- SamplingMessage(role="user", content=ImageContent(type="image", data=test_image_b64, mimeType="image/png"))
- ],
- maxTokens=100,
- )
-
- # Test the sampling callback
- result = await actor._sampling_callback(mock_context, sample_params) # type: ignore[attr-defined]
-
- # Verify the result is an error due to vision not being supported
- assert isinstance(result, ErrorData)
- # Check both the message and data fields for vision/image-related error
- error_text = (result.message + " " + str(result.data or "")).lower()
- assert "vision" in error_text or "image" in error_text
-
-
-async def test_sampling_callback_model_client_error(sample_server_params: StdioServerParams) -> None:
- """Test sampling_callback handles model client errors gracefully."""
- from unittest.mock import AsyncMock, MagicMock
-
- from autogen_ext.tools.mcp._actor import McpSessionActor
- from mcp.shared.context import RequestContext
- from mcp.types import CreateMessageRequestParams, ErrorData, SamplingMessage, TextContent
-
- # Create a model client that will fail
- failing_model_client = MockChatCompletionClient()
- failing_model_client.create = AsyncMock(side_effect=Exception("Model API error")) # type: ignore[method-assign]
-
- # Create an actor with the failing model client
- actor = McpSessionActor(sample_server_params, model_client=failing_model_client)
-
- # Create mock request context and parameters
- mock_context = MagicMock(spec=RequestContext)
- sample_params = CreateMessageRequestParams(
- messages=[SamplingMessage(role="user", content=TextContent(type="text", text="Hello"))], maxTokens=100
- )
-
- # Test the sampling callback
- result = await actor._sampling_callback(mock_context, sample_params) # type: ignore[attr-defined]
-
- # Verify the result is an error
- assert isinstance(result, ErrorData)
- assert result.data is not None and "Model API error" in str(result.data)
-
-
-async def test_sampling_callback_integration_through_session(sample_server_params: StdioServerParams) -> None:
- """Test that shows how sampling_callback should work when properly integrated with session."""
- import asyncio
- from unittest.mock import AsyncMock, MagicMock, patch
-
- # Create a mock model client
- mock_model_client = MagicMock()
- mock_model_client.model_info = {"family": "test", "vision": False}
- mock_model_client.create = AsyncMock(return_value=MagicMock(content="Mock response", finish_reason="stop"))
-
- # Mock the session creation to verify the sampling_callback is passed
- with patch("autogen_ext.tools.mcp._actor.create_mcp_server_session") as mock_session_factory:
- # Create mock session that properly handles the context manager protocol
- mock_session = AsyncMock()
- mock_session.initialize = AsyncMock()
- mock_session.__aenter__ = AsyncMock(return_value=mock_session)
- mock_session.__aexit__ = AsyncMock(return_value=None)
- mock_session_factory.return_value = mock_session
-
- from autogen_ext.tools.mcp._actor import McpSessionActor
-
- actor = McpSessionActor(sample_server_params, model_client=mock_model_client)
-
- # Initialize the actor (this will call create_mcp_server_session)
- await actor.initialize()
-
- # Wait a moment for the actor to initialize
- await asyncio.sleep(0.1)
-
- # Verify that the session was created with the sampling_callback
- mock_session_factory.assert_called_once_with(sample_server_params, sampling_callback=actor._sampling_callback) # type: ignore[attr-defined]
-
- # Clean up by trying to close the actor gracefully
- if actor._active and actor._actor_task is not None: # type: ignore[attr-defined]
- try:
- await actor.close()
- except Exception:
- # Ignore cleanup errors since the main assertion passed
- pass