Skip to content

load_mcp_json

Load MCP server configurations from .mcp.json files.

Quick Example

from mamba_agents.mcp import load_mcp_json, MCPClientManager

# Load configs from file
configs = load_mcp_json(".mcp.json")

# Use with manager
manager = MCPClientManager(configs)

File Format

The .mcp.json format is compatible with Claude Desktop:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/project"],
      "env": {"NODE_ENV": "production"}
    },
    "web-search": {
      "url": "http://localhost:8080/sse"
    }
  }
}

Field Mapping

.mcp.json Field MCPServerConfig Field
(object key) name
command command
args args
env env_vars
url url
tool_prefix tool_prefix
env_file env_file

Transport is auto-detected: url present → SSE, command present → stdio.

Extended Fields

Mamba-agents extends the standard format with:

  • tool_prefix - Prefix for tool names from this server
  • env_file - Path to .env file for environment variables
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem"],
      "tool_prefix": "fs",
      "env_file": ".env.local"
    }
  }
}

Error Handling

from mamba_agents.mcp import (
    load_mcp_json,
    MCPFileNotFoundError,
    MCPFileParseError,
    MCPServerValidationError,
)

try:
    configs = load_mcp_json(".mcp.json")
except MCPFileNotFoundError:
    print("File not found")
except MCPFileParseError as e:
    print(f"Invalid JSON: {e}")
except MCPServerValidationError as e:
    print(f"Invalid server config: {e}")

Path Expansion

The function supports ~ expansion for home directory:

# Both work
configs = load_mcp_json("~/.mcp.json")
configs = load_mcp_json("/home/user/.mcp.json")

API Reference

load_mcp_json

load_mcp_json(path: str | Path) -> list[MCPServerConfig]

Load MCP server configurations from a .mcp.json file.

Parses the .mcp.json file format (compatible with Claude Desktop) and converts entries to MCPServerConfig instances.

PARAMETER DESCRIPTION
path

Path to the .mcp.json file. Can be a string or Path object. Supports ~ expansion for user home directory.

TYPE: str | Path

RETURNS DESCRIPTION
list[MCPServerConfig]

List of MCPServerConfig instances.

RAISES DESCRIPTION
MCPFileNotFoundError

If the file does not exist.

MCPFileParseError

If the file is not valid JSON.

MCPServerValidationError

If a server entry is invalid.

Example

configs = load_mcp_json(".mcp.json") manager = MCPClientManager(configs) agent = Agent("gpt-4o", toolsets=manager.as_toolsets())

Supported .mcp.json format: { "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/project"], "env": {"NODE_ENV": "production"} }, "web-search": { "url": "http://localhost:8080/sse", "tool_prefix": "web" } } }

Source code in src/mamba_agents/mcp/loader.py
def load_mcp_json(path: str | Path) -> list[MCPServerConfig]:
    """Load MCP server configurations from a .mcp.json file.

    Parses the .mcp.json file format (compatible with Claude Desktop) and
    converts entries to MCPServerConfig instances.

    Args:
        path: Path to the .mcp.json file. Can be a string or Path object.
              Supports ~ expansion for user home directory.

    Returns:
        List of MCPServerConfig instances.

    Raises:
        MCPFileNotFoundError: If the file does not exist.
        MCPFileParseError: If the file is not valid JSON.
        MCPServerValidationError: If a server entry is invalid.

    Example:
        >>> configs = load_mcp_json(".mcp.json")
        >>> manager = MCPClientManager(configs)
        >>> agent = Agent("gpt-4o", toolsets=manager.as_toolsets())

    Supported .mcp.json format:
        {
          "mcpServers": {
            "filesystem": {
              "command": "npx",
              "args": ["-y", "@modelcontextprotocol/server-filesystem", "/project"],
              "env": {"NODE_ENV": "production"}
            },
            "web-search": {
              "url": "http://localhost:8080/sse",
              "tool_prefix": "web"
            }
          }
        }
    """
    # Expand ~ and resolve path
    file_path = Path(path).expanduser()

    # Check file exists
    if not file_path.exists():
        raise MCPFileNotFoundError(f"MCP config file not found: {file_path}")

    # Read and parse JSON
    try:
        content = file_path.read_text(encoding="utf-8")
        data: dict[str, Any] = json.loads(content)
    except json.JSONDecodeError as e:
        raise MCPFileParseError(f"Invalid JSON in {file_path}: {e}") from e

    # Parse with Pydantic model
    try:
        mcp_file = MCPJsonFile.model_validate(data)
    except ValueError as e:
        raise MCPServerValidationError(f"Invalid MCP config structure: {e}") from e

    # Convert entries to MCPServerConfig
    configs: list[MCPServerConfig] = []
    for name, entry in mcp_file.mcpServers.items():
        try:
            config = _entry_to_config(name, entry)
            configs.append(config)
        except ValueError as e:
            raise MCPServerValidationError(f"Invalid server '{name}': {e}") from e

    return configs