MCPApp - Model Context Protocol

The MCPApp provides seamless integration with Model Context Protocol (MCP) servers, allowing Meta Agents Research Environments to connect to and utilize tools from any MCP-compatible server. This enables modular tool organization and dynamic tool discovery.

Overview

The Model Context Protocol (MCP) is a standardized way for applications to provide tools and resources to AI systems. The MCPApp acts as a bridge between Meta Agents Research Environments and MCP servers, automatically discovering available tools and exposing them as Meta Agents Research Environments app tools.

Key features:

  • Universal Compatibility: Works with any MCP-compatible server

  • Dynamic Discovery: Automatically discovers tools, resources, and prompts

  • Flexible Connection: Supports both stdio and Server-Sent Events (SSE) connections

  • Tool Filtering: Filter tools by read-only status or exclude specific tools

  • Rich Annotations: Preserves MCP tool annotations for better tool understanding

When to Use Apps vs MCP

Choose MCP Tools When:

  • Integrating with existing MCP servers

  • Need specific, atomic operations

  • Working with external services that provide MCP interfaces

  • Rapid prototyping of new functionality

  • Leveraging community-developed tools

  • No need for scenario reproducibility

Choose Meta Agents Research Environments Apps When:

  • Modeling complete applications or systems

  • Need complex state management

  • Require inter-app communication

  • Building simulation-specific functionality

  • Need fine-grained control over tool behavior and presentation

  • Need to reproduce scenarios across multiple runs

Hybrid Approach:

The most powerful approach often combines both:

# Custom Meta Agents Research Environments app for core functionality
email_app = EmailClientApp()

# MCP integration for external services
code_exec = MCPApp(name="CodeExecution", server_command="code-mcp-server")
wiki_mcp = MCPApp(name="Wikipedia", server_command="wikipedia-mcp-server")

# All work together in the same simulation
scenario = Scenario(apps=[email_app, code_exec, wiki_mcp])

This hybrid approach provides the best of both worlds: the rich application modeling of Meta Agents Research Environments Apps combined with the extensive ecosystem and standardization of MCP tools.

Connection Types

The MCPApp supports two connection methods:

Stdio Connection (Local Servers)

For local MCP servers that communicate via standard input/output:

from are.simulation.apps.mcp.mcp_app import MCPApp

# Connect to a local Python MCP server
math_app = MCPApp(
    name="MathTools",
    server_command="python",
    server_args=["path/to/math_server.py"],
    server_env={"PYTHONPATH": "/custom/path"}  # Optional environment variables
)

SSE Connection (Remote Servers)

For remote MCP servers accessible via HTTP Server-Sent Events:

# Connect to a remote MCP server
code_app = MCPApp(
    name="CodeExecution",
    server_url="http://localhost:8000/sse"
)

Authentication

The MCPApp supports authentication for remote MCP servers through HTTP headers. Currently, long-lived tokens are supported for authentication. OAuth2 support is not available at this time.

Long-Lived Token Authentication

For servers that require authentication via long-lived tokens (such as Home Assistant), you can provide authentication headers when creating the MCPApp:

# Example: Home Assistant MCP server with long-lived token
ha_app = MCPApp(
    name="Home Assistant",
    server_url="http://192.168.0.189:8123/mcp_server/sse",
    sse_headers={
        "Authorization": "Bearer YOURLONGLIVEDTOKENS",
    }
)

The sse_headers parameter accepts a dictionary of HTTP headers that will be sent with each request to the MCP server. This allows for flexible authentication methods depending on your server’s requirements.

Note

OAuth2 authentication is not currently supported. For now, use long-lived tokens or API keys provided by your MCP server.

Configuration Options

The MCPApp provides extensive configuration options for different use cases:

Basic Configuration

app = MCPApp(
    name="MyMCPApp",                    # App name in Meta Agents Research Environments
    server_command="python",            # Command to run the server
    server_args=["server.py"],          # Arguments for the server
    timeout=10.0                        # Timeout for operations
)

Advanced Configuration

app = MCPApp(
    name="FilteredApp",
    server_command="python",
    server_args=["server.py"],
    server_env={"DEBUG": "1"},          # Environment variables
    exclude_tools=["dangerous_tool"],   # Tools to exclude
    only_read_only=True,                # Only include read-only tools
    description_modifier=custom_desc    # Function to modify descriptions
)

Tool Filtering

The MCPApp provides powerful filtering capabilities. Excluding some tools or keep only_read_only, can help use MCPApps in a safer and reproducible way:

Read-Only Filtering

Filter tools to only include those marked as read-only:

# Only expose read-only tools (safe for exploration)
readonly_app = MCPApp(
    name="SafeTools",
    server_command="python",
    server_args=["server.py"],
    only_read_only=True
)

Tool Exclusion

Exclude specific tools by name:

# Exclude potentially dangerous tools
filtered_app = MCPApp(
    name="FilteredTools",
    server_command="python",
    server_args=["server.py"],
    exclude_tools=["delete_file", "format_disk"]
)

Description Modification

Customize tool descriptions dynamically:

def enhance_description(tool_name: str, original_desc: str) -> str:
    if tool_name == "divide":
        return f"{original_desc} (Note: Does not work with negative numbers)"
    return original_desc

app = MCPApp(
    name="EnhancedTools",
    server_command="python",
    server_args=["server.py"],
    description_modifier=enhance_description
)

API Reference

class are.simulation.apps.mcp.mcp_app.MCPApp(name=None, server_command=None, server_args=None, server_env=None, server_url=None, sse_headers=None, description_modifier=None, exclude_tools=None, only_read_only=False, timeout=10.0)[source]

Bases: App

A Meta Agents Research Environments app that connects to an MCP server and exposes its tools.

This app allows Meta Agents Research Environments to interact with any MCP-compatible server, making the server’s tools available as Meta Agents Research Environments app tools.

Initialize the MCP app and connect to the server immediately.

Parameters:
  • name (Optional[str]) – Optional name for the app. Defaults to “MCPApp”.

  • server_command (Optional[str]) – The command to run the MCP server for stdio connection.

  • server_args (Optional[list[str]]) – Arguments to pass to the server command.

  • server_env (Optional[dict[str, str]]) – Environment variables to set for the server.

  • server_url (Optional[str]) – URL for SSE server connection. If provided, stdio parameters are ignored.

  • sse_headers (Optional[dict[str, Any]]) – If using an SSE server, you can pass connection headers (httpx headers).

  • description_modifier (Optional[Callable[[str, str | None], str | None]]) – A function that modifies the description returned by the mcp server. Signature is change_description(tool_name: str, server_description: str | None) -> str | None

  • exclude_tools (Optional[list[str]]) – List of tool names to exclude from the app.

  • only_read_only (bool) – If True, only include tools marked as read-only.

  • timeout (float) – Timeout in seconds for async operations. Defaults to 10.0.

get_state()[source]

Get the current state of the app for serialization.

Returns:

A dictionary containing the app’s state.

Return type:

dict[str, Any]

load_state(state_dict)[source]

Load the app’s state from a dictionary.

Parameters:

state_dict (dict[str, Any]) – A dictionary containing the app’s state.

T = ~T
connect()[source]
close()[source]

Close all connections and clean up resources synchronously.

This method should be called when the app is no longer needed.

reset()[source]

Reset the app to its initial state.

list_resources()[source]

List all available resources from the MCP server.

Returns:

A formatted string listing all available resources with their descriptions.

Return type:

str

list_prompts()[source]

List all available prompts from the MCP server.

Returns:

A formatted string listing all available prompts with their descriptions.

Return type:

str

read_resource(resource_uri)[source]

Read a resource from the MCP server.

Parameters:

resource_uri (str) – The URI of the resource to read.

Returns:

The content of the resource as a string.

Return type:

str

Raises:
  • ConnectionError – If the connection to the server times out.

  • Exception – Any other exception raised during the resource read.

get_tools_with_attribute(attribute, tool_type)[source]

Override the default implementation to directly use the MCP tools list.

This eliminates the need for dynamic method creation and discovery.

Parameters:
  • attribute (ToolAttributeName) – The attribute to look for in the tools as a ToolAttributeName enum value.

  • tool_type (ToolType) – The type of tool being registered (e.g., “APP”, “USER”, “ENV”).

Returns:

A list of AppTool objects created from the MCP tools.

Return type:

list[AppTool]

MCPApp Class

class are.simulation.apps.mcp.mcp_app.MCPApp(name=None, server_command=None, server_args=None, server_env=None, server_url=None, sse_headers=None, description_modifier=None, exclude_tools=None, only_read_only=False, timeout=10.0)[source]

Bases: App

A Meta Agents Research Environments app that connects to an MCP server and exposes its tools.

This app allows Meta Agents Research Environments to interact with any MCP-compatible server, making the server’s tools available as Meta Agents Research Environments app tools.

Initialize the MCP app and connect to the server immediately.

Parameters:
  • name (Optional[str]) – Optional name for the app. Defaults to “MCPApp”.

  • server_command (Optional[str]) – The command to run the MCP server for stdio connection.

  • server_args (Optional[list[str]]) – Arguments to pass to the server command.

  • server_env (Optional[dict[str, str]]) – Environment variables to set for the server.

  • server_url (Optional[str]) – URL for SSE server connection. If provided, stdio parameters are ignored.

  • sse_headers (Optional[dict[str, Any]]) – If using an SSE server, you can pass connection headers (httpx headers).

  • description_modifier (Optional[Callable[[str, str | None], str | None]]) – A function that modifies the description returned by the mcp server. Signature is change_description(tool_name: str, server_description: str | None) -> str | None

  • exclude_tools (Optional[list[str]]) – List of tool names to exclude from the app.

  • only_read_only (bool) – If True, only include tools marked as read-only.

  • timeout (float) – Timeout in seconds for async operations. Defaults to 10.0.

__init__(name=None, server_command=None, server_args=None, server_env=None, server_url=None, sse_headers=None, description_modifier=None, exclude_tools=None, only_read_only=False, timeout=10.0)[source]

Initialize the MCP app and connect to the server immediately.

Parameters:
  • name (Optional[str]) – Optional name for the app. Defaults to “MCPApp”.

  • server_command (Optional[str]) – The command to run the MCP server for stdio connection.

  • server_args (Optional[list[str]]) – Arguments to pass to the server command.

  • server_env (Optional[dict[str, str]]) – Environment variables to set for the server.

  • server_url (Optional[str]) – URL for SSE server connection. If provided, stdio parameters are ignored.

  • sse_headers (Optional[dict[str, Any]]) – If using an SSE server, you can pass connection headers (httpx headers).

  • description_modifier (Optional[Callable[[str, str | None], str | None]]) – A function that modifies the description returned by the mcp server. Signature is change_description(tool_name: str, server_description: str | None) -> str | None

  • exclude_tools (Optional[list[str]]) – List of tool names to exclude from the app.

  • only_read_only (bool) – If True, only include tools marked as read-only.

  • timeout (float) – Timeout in seconds for async operations. Defaults to 10.0.

get_state()[source]

Get the current state of the app for serialization.

Returns:

A dictionary containing the app’s state.

Return type:

dict[str, Any]

load_state(state_dict)[source]

Load the app’s state from a dictionary.

Parameters:

state_dict (dict[str, Any]) – A dictionary containing the app’s state.

T = ~T
connect()[source]
close()[source]

Close all connections and clean up resources synchronously.

This method should be called when the app is no longer needed.

reset()[source]

Reset the app to its initial state.

list_resources()[source]

List all available resources from the MCP server.

Returns:

A formatted string listing all available resources with their descriptions.

Return type:

str

list_prompts()[source]

List all available prompts from the MCP server.

Returns:

A formatted string listing all available prompts with their descriptions.

Return type:

str

read_resource(resource_uri)[source]

Read a resource from the MCP server.

Parameters:

resource_uri (str) – The URI of the resource to read.

Returns:

The content of the resource as a string.

Return type:

str

Raises:
  • ConnectionError – If the connection to the server times out.

  • Exception – Any other exception raised during the resource read.

get_tools_with_attribute(attribute, tool_type)[source]

Override the default implementation to directly use the MCP tools list.

This eliminates the need for dynamic method creation and discovery.

Parameters:
  • attribute (ToolAttributeName) – The attribute to look for in the tools as a ToolAttributeName enum value.

  • tool_type (ToolType) – The type of tool being registered (e.g., “APP”, “USER”, “ENV”).

Returns:

A list of AppTool objects created from the MCP tools.

Return type:

list[AppTool]

failure_probability: float | None

Tool Utility Classes

class are.simulation.tool_utils.AppTool(class_name, app_name, name, function_description, args, return_type=None, return_description=None, function=None, class_instance=None, write_operation=None, _public_name=None, _public_description=None, failure_probability=None, failure_message_template='Calling {name} failed with error: Internal error - Retry again later', seed=None, rng=None)[source]

Bases: object

class_name: str
app_name: str
name: str
function_description: str | None
args: list[AppToolArg]
return_type: Optional[Any] = None
return_description: str | None = None
function: Optional[Callable] = None
class_instance: Optional[Any] = None
write_operation: bool | None = None
failure_probability: float | None = None
failure_message_template: str = 'Calling {name} failed with error: Internal error - Retry again later'
seed: int | None = None
rng: Random | None = None
property arg_descriptions: str
property func_name
static get_tool_for_function(func)[source]

Get the AppTool instance associated with a function.

Return type:

AppTool | None

to_metadata_dict()[source]

Returns a dictionary representation of the tool’s metadata. This is used for serialization and UI display.

to_open_ai()[source]

Convert the tool to OpenAI function calling format.

Example:

{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["location"]
        }
    }
}
class are.simulation.tool_utils.ToolAttributeName(value)[source]

Bases: Enum

Enum for tool attribute names used by decorators and tool registration.

APP = '_is_app_tool'
ENV = '_is_env_tool'
DATA = '_is_data_tool'
USER = '_is_user_tool'

MCP Tool Annotations

The MCPApp preserves and exposes MCP tool annotations, providing rich metadata about tool behavior:

Annotation Types

  • readOnlyHint: Whether the tool modifies its environment

  • destructiveHint: Whether modifications are destructive or additive

  • idempotentHint: Whether repeated calls have the same effect

  • openWorldHint: Whether the tool interacts with external entities

  • title: Human-readable title for the tool

The MCPApp provides a powerful and flexible way to extend Meta Agents Research Environments with external tools while maintaining safety and control through comprehensive filtering and annotation support.