### Run MCP Gateway Server Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/README.md Command-line examples for starting the MCP Gateway with various options. These include enabling plugins, security scanning, tracing, and setting debug mode. ```bash # Start with basic guardrail mcp-gateway --mcp-json-path ~/.cursor/mcp.json --plugin basic ``` ```bash # With security scanning mcp-gateway --mcp-json-path ~/.cursor/mcp.json --scan --plugin basic ``` ```bash # With tracing mcp-gateway --mcp-json-path ~/.cursor/mcp.json --plugin basic --plugin xetrack ``` ```bash # Debug mode LOGLEVEL=DEBUG mcp-gateway --mcp-json-path ~/.cursor/mcp.json --plugin basic ``` -------------------------------- ### Example Tool Parameter List Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/types.md Provides an example of how to structure a list of tool parameters, where each parameter is a ToolParamTuple. ```python params = [ ("path", str, "File path to read"), ("encoding", str, "Character encoding (default: utf-8)"), ] ``` -------------------------------- ### Example Server Configuration (Python) Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/types.md An example of a dictionary representing the configuration for a proxied server, specifying the command, arguments, and environment. ```python { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], "env": None, "blocked": "passed" } ``` -------------------------------- ### Start MCP Server Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/server.md Starts the MCP server, establishes a client session, and fetches initial capabilities. Ensure the server configuration is correctly set up before calling. ```python import asyncio from mcp_gateway.server import Server server = Server("filesystem", config) await server.start() print(f"Server {server.name} started successfully") ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/INDEX.md A basic example of a JSON configuration object. ```json {"key": "value"} ``` -------------------------------- ### Create and Start MCP Server Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/README.md Initializes and starts an MCP server instance. This is typically done after loading the configuration. ```python from mcp_gateway.server import Server server = Server("filesystem", servers["filesystem"]) await server.start() # Use server... await server.stop() ``` -------------------------------- ### Shell Command Example Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/INDEX.md Shows how to run the mcp-gateway command-line tool with the help flag. ```bash mcp-gateway --help ``` -------------------------------- ### Example Gateway Context Initialization (Python) Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/types.md Demonstrates how to initialize the GatewayContext with specific proxied servers, a plugin manager, and the path to the mcp.json file. ```python context = GetewayContext( proxied_servers={"filesystem": server}, plugin_manager=manager, mcp_json_path="~/.cursor/mcp.json" ) ``` -------------------------------- ### Run MCP Gateway with Xetrack enabled Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Use this command to start the MCP Gateway with Xetrack tracing enabled. Ensure Xetrack is installed. ```bash mcp-gateway -p xetrack ``` -------------------------------- ### Server Start Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/server.md Starts the underlying MCP server process, establishes a client session, and fetches initial capabilities (tools, resources, prompts). ```APIDOC ## start ### Description Starts the underlying MCP server process, establishes a client session, and fetches initial capabilities (tools, resources, prompts). ### Method `async def start(self) -> None` ### Returns None ### Raises - `Exception`: If server startup fails (logged and cleaned up) ### Example ```python import asyncio from mcp_gateway.server import Server server = Server("filesystem", config) await server.start() print(f"Server {server.name} started successfully") ``` ``` -------------------------------- ### Start and Manage an MCP Server Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/README.md Use the Server class to initialize, start, and interact with a proxied MCP server. It allows listing tools and calling them. ```python server = Server("filesystem", { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] }) await server.start() tools = server.list_tools() result = await server.call_tool(plugin_manager, "read_file", {"path": "/tmp/file"}) await server.stop() ``` -------------------------------- ### Example MCP Tool Definition Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/types.md An example of how to instantiate a `types.Tool` object for a 'read_file' capability. ```python tool = types.Tool( name="read_file", description="Read the contents of a file", inputSchema={ "type": "object", "properties": { "path": { "type": "string", "description": "Path to the file" } }, "required": ["path"] } ) ``` -------------------------------- ### Install MCP Gateway Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/README.md Use pip to install the MCP Gateway. Install with optional plugins like 'presidio' for PII detection or 'xetrack' for tracing. For development, use the 'dev' extra. ```bash pip install mcp-gateway ``` ```bash pip install mcp-gateway[presidio] ``` ```bash pip install mcp-gateway[xetrack] ``` ```bash pip install mcp-gateway[presidio,xetrack] ``` ```bash pip install mcp-gateway[dev] ``` -------------------------------- ### Python Import Example Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/INDEX.md Demonstrates how to import the Server class from the mcp_gateway.server module. ```python from mcp_gateway.server import Server ``` -------------------------------- ### Start Basic MCP Gateway Server Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Starts the MCP Gateway server with the 'basic' and 'presidio' plugins enabled. Use this for general security and PII masking. ```bash mcp-gateway -p basic -p presidio ``` -------------------------------- ### MCP Gateway Configuration with Security Scanning Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/config.md Configuration example for the MCP Gateway that includes security scanning plugins and environment variables for API keys. This setup enables the 'lasso' plugin for security. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--scan", "--plugin", "basic", "--plugin", "lasso" ], "env": { "LASSO_API_KEY": "your-api-key" }, "servers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] } } } } } ``` -------------------------------- ### Install mcp-gateway Package Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Install the mcp-gateway package using pip. This is the recommended installation method for Python. ```bash pip install mcp-gateway ``` -------------------------------- ### PluginContext Example Usage Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/plugins.md Illustrates the instantiation and conversion of a PluginContext object. ```python context = PluginContext( server_name="filesystem", capability_type="tool", capability_name="read_file", arguments={"path": "/tmp/file.txt"} ) context_dict = context.to_dict() ``` -------------------------------- ### Security Scanner Example Usage Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/security-scanner.md Demonstrates the full lifecycle of using the Security Scanner, from loading configurations and scanning reputations to initializing servers and scanning their tools. ```python from mcp_gateway.security_scanner.scanner import Scanner from mcp_gateway.config import load_config from mcp_gateway.server import GetewayContext, Server # Initialize scanner scanner = Scanner() # 1. Scan reputation before starting servers servers_config = load_config("~/.cursor/mcp.json") servers_config = scanner.scan_mcps_reputation( servers_config, "~/.cursor/mcp.json" ) # 2. Create server instances (skip blocked ones) context = GetewayContext() for name, config in servers_config.items(): if config.get("blocked") != "blocked": server = Server(name, config) context.proxied_servers[name] = server # 3. Start servers and scan tools # (after servers are running) context = scanner.scan_server_tools(context) # 4. Use context with gateway for name, server in context.proxied_servers.items(): if server.blocked == "passed": print(f"Server {name} is safe") ``` -------------------------------- ### Start Basic Guardrail Plugin Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Starts the MCP Gateway server with only the 'basic' guardrail plugin. This plugin masks common secrets like API keys and tokens. ```bash mcp-gateway -p basic ``` -------------------------------- ### Example Usage of get_metadata Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/gateway.md Demonstrates how to call the get_metadata tool and iterate through the returned server information to display active servers and their tool counts. ```python metadata = await get_metadata(ctx) for server_name, server_info in metadata.items(): if server_info["status"] == "active": print(f"{server_name}: {len(server_info['original_tools'])} tools") ``` -------------------------------- ### Run mcp-gateway with Plugins Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Example of running the mcp-gateway with the basic guardrail for token masking and the xetrack tracing plugin for filesystem MCP. Use `--mcp-json-path` to specify the configuration file and `-p` or `--plugin` to enable plugins. ```bash mcp-gateway --mcp-json-path ~/.mcp.json -p basic -p xetrack ``` -------------------------------- ### Server Configuration JSON Example Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/config.md Defines the structure for configuring a proxied server, including the executable command, its arguments, environment variables, and a blocked status. ```json { "my_server": { "command": "python", "args": ["-m", "my_mcp_module"], "env": { "API_KEY": "secret", "DEBUG": "true" }, "blocked": "passed" } } ``` -------------------------------- ### Tool Input Schema Example Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/config.md An example of a tool definition including its input schema in JSON format. This schema specifies the expected parameters, their types, and descriptions. ```python tool = types.Tool( name="read_file", description="Read a file", inputSchema={ "type": "object", "properties": { "path": { "type": "string", "description": "File path to read" }, "encoding": { "type": "string", "description": "File encoding (default: utf-8)" } } } ) ``` -------------------------------- ### Configuration with Xetrack Tracing Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Example configuration for enabling Xetrack tracing. This includes setting environment variables for the database path, logs path, and flattening options for arguments and responses. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--plugin", "basic", "--plugin", "xetrack" ], "env": { "XETRACK_DB_PATH": "./tracing.db", "XETRACK_LOGS_PATH": "./logs", "FLATTEN_ARGUMENTS": "true", "FLATTEN_RESPONSE": "true" }, "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Start Debug MCP Gateway Server Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Starts the MCP Gateway server in debug mode with a specified JSON path for configuration. Useful for troubleshooting. ```bash LOGLEVEL=DEBUG mcp-gateway --mcp-json-path ~/.cursor/mcp.json -p basic -p presidio ``` -------------------------------- ### Typical MCP Gateway Configuration (Claude Desktop) Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/config.md Example configuration for the MCP Gateway tailored for Claude Desktop. It specifies the command to run the gateway server and includes a filesystem server. ```json { "mcpServers": { "mcp-gateway": { "command": "python", "args": [ "-m", "mcp_gateway.server", "--mcp-json-path", "~/.config/Claude/claude_desktop_config.json", "--plugin", "basic" ], "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Tool Parameter Extraction Example Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/config.md Demonstrates how to use the `get_tool_params_description` function to extract parameter information from a tool's input schema and print the extracted details. ```python from mcp_gateway.config import get_tool_params_description params = get_tool_params_description(tool) for param_name, param_type, description in params: type_name = param_type.__name__ if hasattr(param_type, '__name__') else str(param_type) print(f"{param_name}: {type_name}") print(f" {description}") ``` -------------------------------- ### Basic Guardrail Configuration Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Example configuration for the MCP Gateway with the basic guardrail plugin. This sets up the gateway command, JSON path, and a filesystem server. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--plugin", "basic" ], "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Example Guardrail Plugin Implementation Source: https://github.com/lasso-security/mcp-gateway/blob/main/mcp_gateway/plugins/README.md Implement a custom guardrail plugin by extending GuardrailPlugin and using the @register_plugin decorator. This example shows how to define plugin name, load configuration, and process requests and responses. ```python from typing import Any, Dict, Optional from mcp_gateway.plugins.base import GuardrailPlugin, PluginContext from mcp_gateway.plugins.manager import register_plugin import logging logger = logging.getLogger(__name__) @register_plugin class MyGuardrailPlugin(GuardrailPlugin): """A custom guardrail plugin that blocks certain operations.""" # Both class name and plugin_name are used for command-line arguments # So either '--plugin MyGuardrail' or '--plugin my-guardrail' will work plugin_name = "my-guardrail" def load(self, config: Optional[Dict[str, Any]] = None) -> None: """Configure the plugin with optional settings.""" logger.info("MyGuardrailPlugin loaded") def process_request(self, context: PluginContext) -> Optional[Dict[str, Any]]: """Process a request before it's sent to the server.""" # Return None to block the request, or return modified arguments return context.arguments def process_response(self, context: PluginContext) -> Any: """Process a response before it's returned to the client.""" # Return modified response return context.response ``` -------------------------------- ### Initialize Security Scanner During Gateway Startup Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/security-scanner.md The security scanner is initialized and used within the gateway's lifespan function. It scans server reputation before servers start and server tools after servers are started. Ensure `cli_args` and `cli_args.scan` are available and that `cli_args.mcp_json_path` is correctly set. ```python from mcp_gateway.security_scanner.scanner import Scanner # In gateway.py lifespan function if cli_args and cli_args.scan: scanner = Scanner() # Scan reputation before starting servers proxied_server_configs = scanner.scan_mcps_reputation( proxied_server_configs, cli_args.mcp_json_path ) # Later, scan tools after servers are started context = scanner.scan_server_tools(context) ``` -------------------------------- ### Create Token File Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Creates a file named 'tokens.txt' containing a Hugging Face token. This is a setup step for testing sensitive information masking. ```bash echo 'HF_TOKEN = "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"' > tokens.txt ``` -------------------------------- ### Typical MCP Gateway Configuration (Cursor) Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/config.md Example of a typical configuration file for the MCP Gateway, specifically for use with Cursor. This includes server definitions for filesystem and fetch operations. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--plugin", "basic" ], "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] }, "fetch": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-fetch" ] } } } } } ``` -------------------------------- ### Configuration with Security Scanning and Lasso Plugin Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Example configuration enabling security scanning and the Lasso plugin. It includes environment variables for the Lasso API key and specifies blocking status for filesystem and fetch servers. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--scan", "--plugin", "basic", "--plugin", "lasso" ], "env": { "LASSO_API_KEY": "your-api-key-here" }, "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ], "blocked": "passed" }, "fetch": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-fetch" ], "blocked": "passed" } } } } } ``` -------------------------------- ### Correct Server Session Access Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/errors.md Ensure `server.start()` is awaited before accessing `server.session`. Accessing the session property before starting the server will result in a RuntimeError. ```python # Wrong result = server.session.call_tool(...) # Correct await server.start() result = await server.session.call_tool(...) ``` -------------------------------- ### Custom LoggingPlugin Implementation Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/plugins.md Provides a concrete example of a Tracing plugin that logs request and response information. ```python from mcp_gateway.plugins.base import Plugin, PluginContext class LoggingPlugin(Plugin): plugin_type = "tracing" plugin_name = "logging" def load(self, config=None): self.enabled = config.get("enabled", True) if config else True def process_request(self, context: PluginContext): if self.enabled: print(f"Request: {context.server_name}/{context.capability_name}") return context.arguments def process_response(self, context: PluginContext): if self.enabled: print(f"Response: {context.capability_name}") return context.response ``` -------------------------------- ### Query Xetrack Database with CLI Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Example of using the Xetrack CLI to view the latest traced event in JSON format. This helps in inspecting tool calls and their responses. ```bash $ xt tail tracing.db --json --n=1 [ { "timestamp": "2025-04-17 17:12:48.233126", "track_id": "mottled-stingray-0411", "meta": "f3be31e09667745f", "paths": null, "call_id": "deab617e-0a45-4950-9de9-3fb549810cf2", "capability_name": "list_directory", "content_type": "text", "content_annotations": "f3be31e09667745f", "response_type": "CallToolResult", "server_name": "filesystem", "capability_type": "tool", "isError": 0, "content_text": "[DIR] .cursor\n[DIR] .git\n[FILE] .gitignore\n[DIR] .pytest_cache\n[DIR] .venv\n[FILE] LICENSE\n[FILE] MANIFEST.in\n[FILE] README.md\n[DIR] docs\n[DIR] logs\n[DIR] mcp_gateway\n[FILE] pyproject.toml\n[FILE] requirements.txt\n[DIR] tests\n[DIR] tmp", "path": ".", "prompt": null } ] ``` -------------------------------- ### Get Server Capabilities Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/server.md Fetches the capabilities of the proxied server. This information is derived from the stored InitializeResult. Returns server capabilities or None if unavailable. ```python async def get_capabilities(self) -> Optional[types.ServerCapabilities]: # ... implementation details ... pass ``` ```python caps = await server.get_capabilities() if caps.tools: print(f"Server supports {len(caps.tools)} tools") ``` -------------------------------- ### Run MCP Gateway with Docker Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Example of running the mcp-gateway using Docker. This configuration mounts local directories, passes environment variables, and enables specific plugins. Use `INSTALL_EXTRAS` to include optional dependencies like 'presidio' or 'xetrack'. ```json { "mcpServers": { "mcp-gateway": { "command": "docker", "args": [ "run", "--rm", "--mount", "type=bind,source=/Users/oro/Projects/playground/mcp-gateway,target=/app", "-i", "-v", "/Users/oro/.cursor/mcp.json:/config/mcp.json:ro", "-e", "LASSO_API_KEY=", "-v", "mcp-gateway-logs:/logs", "mcp/gateway:latest", "--mcp-json-path", "/config/mcp.json", "--plugin", "basic", "--plugin", "lasso" ], "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Example MCP Servers Dictionary JSON Structure Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/types.md Illustrates the expected JSON format for the mcpServers configuration, detailing the nested structure for gateway and server definitions. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [...], "servers": {...} } } } ``` -------------------------------- ### Claude Desktop with PII Detection Configuration Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Configuration for the MCP Gateway enabling PII detection using the 'presidio' plugin. This example specifies the gateway command, JSON path, and includes a filesystem server. ```json { "mcpServers": { "mcp-gateway": { "command": "python", "args": [ "-m", "mcp_gateway.server", "--mcp-json-path", "~/.config/Claude/claude_desktop_config.json", "--plugin", "basic", "--plugin", "presidio" ], "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Python Server Command Configuration Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Configures a server to run a Python module using the `python -m` command. Ensure the module is installed in the Python environment. ```json { "command": "python", "args": ["-m", "mcp_server_module"] } ``` -------------------------------- ### Main Entry Point for MCP Gateway CLI Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/gateway.md The main entry point for the mcp-gateway command-line tool. It parses arguments and starts the FastMCP server. Supports configuration file path, plugin selection, and security scanning. ```python def main() -> None: pass ``` ```bash mcp-gateway \ --mcp-json-path ~/.cursor/mcp.json \ -p basic \ -p xetrack \ --scan ``` -------------------------------- ### Docker Configuration for MCP Gateway Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Example of how to run the MCP Gateway within a Docker container. This configuration includes volume mounts for the application and configuration, environment variables, and specifies plugins. ```json { "mcpServers": { "mcp-gateway": { "command": "docker", "args": [ "run", "--rm", "--mount", "type=bind,source=/home/user/mcp-gateway,target=/app", "-i", "-v", "/home/user/.cursor/mcp.json:/config/mcp.json:ro", "-e", "LASSO_API_KEY=your-key", "-v", "mcp-gateway-logs:/logs", "mcp/gateway:latest", "--mcp-json-path", "/config/mcp.json", "--plugin", "basic", "--plugin", "lasso" ], "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Initial MCP Gateway Configuration Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Initial JSON configuration for the MCP Gateway, specifying the command, arguments, and server details. This setup is used before the first scan. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--scan" ], "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Configure Lasso Guardrail Plugin Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Example JSON configuration for MCP Gateway to use the 'lasso' guardrail plugin. Requires setting the LASSO_API_KEY environment variable and configuring other MCP servers. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "-p", "lasso" ], "env": { "LASSO_API_KEY": "" }, "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Query Xetrack Database with DuckDB CLI Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Example of using the DuckDB CLI to query the Xetrack SQLite database. This demonstrates attaching the database and performing a SQL query to retrieve specific event details. ```bash $ duckdb --ui D INSTALL sqlite; LOAD sqlite; ATTACH 'tracing.db' (TYPE sqlite); D SELECT server_name,capability_name,path,content_text FROM db.events LIMIT 1; ┌─────────────┬─────────────────┬─────────┬────────────────────────────────────┐ │ server_name │ capability_name │ path │ content_text │ │ varchar │ varchar │ varchar │ varchar │ ├─────────────┼─────────────────┼─────────┼────────────────────────────────────┤ │ filesystem │ list_directory │ . │ [DIR] .cursor\n[DIR] .git\n[FILE… │ └─────────────┴─────────────────┴─────────┴────────────────────────────────────┘ ``` -------------------------------- ### Initialize Server Instance Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/server.md Use this to create a new Server instance. Provide a unique name and a configuration dictionary including the command to run, its arguments, and environment variables. ```python from mcp_gateway.server import Server server_config = { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], "env": None } server = Server("filesystem", server_config) ``` -------------------------------- ### Registering Plugins via Command-Line Arguments Source: https://github.com/lasso-security/mcp-gateway/blob/main/mcp_gateway/plugins/README.md Demonstrates how to enable plugins using command-line arguments, specifying them either by their class name or their registered plugin_name. ```bash mcp-gateway -p MyGuardrailPlugin -p basic # or mcp-gateway -p my-guardrail -p basic ``` -------------------------------- ### Basic Gateway Configuration and Run Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/README.md Configure the gateway in a JSON file (e.g., ~/.cursor/mcp.json) and then run the mcp-gateway command with the specified configuration and basic plugin. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--plugin", "basic" ], "servers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] } } } } } ``` ```bash mcp-gateway --mcp-json-path ~/.cursor/mcp.json --plugin basic ``` -------------------------------- ### Server Constructor Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/server.md Initializes a new Server instance with a given name and configuration. ```APIDOC ## Server.__init__ ### Description Initializes the Proxied Server instance. ### Parameters #### Path Parameters - **name** (str) - Required - Unique identifier for this server instance - **config** (Dict[str, Any]) - Required - Configuration dictionary containing `command`, `args`, `env`, and optionally `blocked` status ### Request Example ```python from mcp_gateway.server import Server server_config = { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], "env": None } server = Server("filesystem", server_config) ``` ``` -------------------------------- ### Enable Plugins via CLI Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Shows how to enable plugins for the MCP Gateway using the --plugin or -p command-line argument. Multiple plugins can be specified. ```bash mcp-gateway -p basic -p xetrack -p lasso ``` ```json { "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--plugin", "basic", "--plugin", "xetrack" ] } ``` -------------------------------- ### Start Presidio Guardrail Plugin Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Starts the MCP Gateway server with the 'presidio' guardrail plugin. This plugin is used for identifying and anonymizing PII like credit card numbers and emails. ```bash mcp-gateway -p presidio ``` -------------------------------- ### Run Gateway with Tracing and PII Detection Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/README.md Launch the mcp-gateway with multiple plugins enabled: 'basic', 'presidio' for PII detection, and 'xetrack' for tracing. Ensure the configuration path is also provided. ```bash mcp-gateway \ --mcp-json-path ~/.cursor/mcp.json \ --plugin basic \ --plugin presidio \ --plugin xetrack ``` -------------------------------- ### Test MCP Gateway Configuration and Environment Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/errors.md Validate your JSON configuration file using `json.tool`, check for the presence of necessary commands like `mcp-gateway`, `npx`, and `python`, and test server startup with `--help`. ```bash # Validate JSON python -m json.tool ~/.cursor/mcp.json # Check command availability which mcp-gateway which npx which python # Test server startup npx @modelcontextprotocol/server-filesystem --help ``` -------------------------------- ### PluginContext Initialization Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/plugins.md Demonstrates the creation of a PluginContext object with essential parameters. ```python class PluginContext: def __init__( self, server_name: str, capability_type: str, capability_name: str, arguments: Optional[Dict[str, Any]] = None, response: Any = None, mcp_context: Optional[Any] = None, ) -> None ``` -------------------------------- ### Root mcp.json Structure Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Defines the top-level structure for mcp.json, specifying gateway server definitions and gateway setup. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [...], "env": {...}, "servers": {...} } } } ``` -------------------------------- ### Import Configuration Modules Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/MODULES.md Imports for configuration loading and parameter description utilities. ```python from mcp_gateway.config import load_config, load_servers_config_from_path, find_config_file ``` ```python from mcp_gateway.config import get_tool_params_description, Constants ``` -------------------------------- ### Server Lifecycle Management Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/INDEX.md Methods for managing the lifecycle of the MCP Gateway server, including starting, stopping, and interacting with tools and resources. ```APIDOC ## Server Class Methods ### `start()` Starts the MCP Gateway server. ### `stop()` Stops the MCP Gateway server. ### `call_tool(tool_name, **kwargs)` Calls a registered tool with the given arguments. ### `list_tools()` Lists all available tools. ### `read_resource(resource_name)` Reads the content of a specified resource. ### `list_resources()` Lists all available resources. ### `get_prompt(prompt_name)` Retrieves a specific prompt. ### `list_prompts()` Lists all available prompts. ### `get_capabilities()` Retrieves the server's capabilities. ``` -------------------------------- ### Handle SanitizationError in a Try-Except Block Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/types.md Example of how to catch and handle a SanitizationError during a server call. This is useful for gracefully managing critical plugin failures. ```python try: result = await server.call_tool(...) except SanitizationError as e: return error_response(str(e)) ``` -------------------------------- ### Configure Lasso API Key via .env File Source: https://github.com/lasso-security/mcp-gateway/blob/main/tests/README.md Set up environment variables for Lasso API key, user ID, and conversation ID by creating a .env file in the project root. ```bash LASSO_API_KEY=your_api_key_here LASSO_USER_ID=optional_user_id LASSO_CONVERSATION_ID=optional_conversation_id ``` -------------------------------- ### Get Plugin Type by Name Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/plugins.md Retrieve the plugin type string for a given plugin name using the `get_plugin_type` function. The lookup is case-insensitive. ```python plugin_type = get_plugin_type("basic") print(f"Plugin 'basic' is type: {plugin_type}") # Output: "guardrail" ``` -------------------------------- ### Get Plugins by Type Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/plugins.md Retrieve all loaded plugins of a specified type. Useful for accessing plugins that perform a particular function, like guardrails or tracing. ```python def get_plugins(self, plugin_type: str) -> List[Plugin] ``` ```python manager = PluginManager( enabled_types=["guardrail"], enabled_plugins={"guardrail": ["basic"]} ) guardrails = manager.get_plugins("guardrail") for plugin in guardrails: print(f"Loaded: {plugin.__class__.__name__}") ``` -------------------------------- ### Initialize Main FastMCP Instance Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/gateway.md Instantiates the main FastMCP server for the gateway. It includes a lifespan context manager for server initialization and cleanup. ```python mcp = FastMCP("MCP Gateway", lifespan=lifespan) ``` -------------------------------- ### Load Server Configurations in Gateway Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/config.md Loads server configurations from a JSON file and initializes Server objects, skipping any servers marked as 'blocked'. ```python from mcp_gateway.config import load_config # In gateway.py lifespan function proxied_server_configs = load_config(cli_args.mcp_json_path) for name, server_config in proxied_server_configs.items(): if server_config.get("blocked") == "blocked": logger.warning(f"Server '{name}' is blocked") continue proxied_server = Server(name, server_config) context.proxied_servers[name] = proxied_server ``` -------------------------------- ### Load Server Configurations from Path Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/config.md Loads proxied server configurations from a specified `mcp.json` file path. It expects a specific JSON structure and extracts server definitions, returning them as a dictionary. ```python from mcp_gateway.config import load_servers_config_from_path from pathlib import Path config_path = Path.home() / ".cursor" / "mcp.json" servers = load_servers_config_from_path(config_path) for name, config in servers.items(): print(f"Server: {name}") print(f" Command: {config['command']}") print(f" Args: {config['args']}") ``` -------------------------------- ### Check if MCP Server is Risky (Smithery) Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/security-scanner.md Use the `is_risky` method to determine if an MCP server is risky. This example demonstrates checking a Smithery-based server configuration. ```python scanner = Scanner() smithery_config = { "command": "uv", "args": ["run", "my-author/my-project"] } is_risky = scanner.is_risky("my_server", smithery_config, "~/.cursor/mcp.json") ``` -------------------------------- ### Check if MCP Server is Risky (NPM) Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/security-scanner.md Use the `is_risky` method to determine if an MCP server is risky. This example demonstrates checking an NPM-based server configuration. ```python scanner = Scanner() npm_config = { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] } is_risky = scanner.is_risky("filesystem", npm_config, "~/.cursor/mcp.json") print(f"Filesystem server risky: {is_risky}") ``` -------------------------------- ### Basic Server Entry Configuration Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Defines a server entry with its execution command, arguments, environment variables, and security status. Use this to configure how a server process is launched. ```json { "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ], "env": null, "blocked": "passed" } } } ``` -------------------------------- ### MCP Gateway Configuration with Path Expansion Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Demonstrates the use of the tilde (~) character for expanding the user's home directory in the `--mcp-json-path` argument. This allows for user-specific configuration file locations. ```json { "args": [ "--mcp-json-path", "~/.cursor/mcp.json" ] } ``` -------------------------------- ### MCP Gateway Configuration (Cursor) Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md JSON configuration for mcp-gateway when used with Cursor. This example enables basic and xetrack plugins and configures a filesystem MCP server. ```json { "mcpServers": { "mcp-gateway": { "command": "mcp-gateway", "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--plugin", "basic", "--plugin", "xetrack" ], "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Set Up XetrackPlugin Environment Variables Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/plugins.md Configure the XetrackPlugin by setting environment variables for the database path, log directory, and argument/response flattening behavior. ```bash export XETRACK_DB_PATH=./tracing.db export XETRACK_LOGS_PATH=./logs mcp-gateway --mcp-json-path ~/.cursor/mcp.json -p xetrack ``` -------------------------------- ### Handle SanitizationError in Python Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/sanitizers.md Example of how to catch and handle a `SanitizationError` when processing tool call arguments. This pattern is useful for gracefully managing blocked requests or policy violations. ```python from mcp_gateway.sanitizers import SanitizationError try: sanitized_args = await sanitize_tool_call_args(...) except SanitizationError as e: print(f"Request blocked: {e}") return error_response ``` -------------------------------- ### Access Client Session Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/server.md Retrieve the active `ClientSession` object for communication with the MCP server using the `session` property. Ensure the session has been started before accessing it to avoid a `RuntimeError`. ```python try: session = server.session except RuntimeError as e: print(f"Session not available: {e}") ``` -------------------------------- ### Direct Executable Server Command Configuration Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Configures a server to run a direct executable file. Provide the absolute or relative path to the executable and its arguments. ```json { "command": "/usr/local/bin/mcp-server", "args": ["--config", "/path/to/config"] } ``` -------------------------------- ### List Available Tools Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/server.md Retrieves a list of tools that are currently available from the proxied server. This list is populated during server startup. ```python tools = server.list_tools() for tool in tools: print(f"Tool: {tool.name}") ``` -------------------------------- ### Get Tool Parameters Description Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/gateway.md Extracts tool parameter information from a tool's inputSchema for dynamic registration. This function maps schema types to Python types. ```python params = get_tool_params_description(tool) for name, typ, desc in params: print(f"{name}: {typ.__name__} - {desc}") ``` -------------------------------- ### Initialize Plugin Manager Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/README.md Instantiate a PluginManager to enable and configure guardrail and tracing plugins for request and response processing. ```python manager = PluginManager( enabled_types=["guardrail", "tracing"], enabled_plugins={"guardrail": ["basic"], "tracing": ["xetrack"]} ) sanitized_args = await manager.process_request(context) sanitized_response = await manager.process_response(context) ``` -------------------------------- ### Enable Security Scanning via CLI Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Illustrates how to enable security scanning for MCP servers before loading using the --scan command-line argument. This includes analyzing server reputation and scanning for tool poisoning. ```bash mcp-gateway --scan --mcp-json-path ~/.cursor/mcp.json ``` ```json { "args": [ "--mcp-json-path", "~/.cursor/mcp.json", "--scan", "--plugin", "basic" ] } ``` -------------------------------- ### List Tools Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/server.md Returns the cached list of tools available from the proxied server, using the list fetched during startup. ```APIDOC ## list_tools ### Description Returns the cached list of tools available from the proxied server. Uses the list fetched during startup. ### Method `def list_tools(self) -> List[types.Tool]` ### Returns List of `types.Tool` objects ### Example ```python tools = server.list_tools() for tool in tools: print(f"Tool: {tool.name}") ``` ``` -------------------------------- ### MCP Gateway Configuration (Claude) Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md JSON configuration for mcp-gateway when used with Claude. This example requires specifying the Python path and enables the basic plugin. It also configures a filesystem MCP server. ```bash which python ``` ```json { "mcpServers": { "mcp-gateway": { "command": "", "args": [ "-m", "mcp_gateway.server", "--mcp-json-path", "", "--plugin", "basic" ], "servers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "." ] } } } } } ``` -------------------------------- ### Scan All MCP Servers for Reputation Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/api-reference/security-scanner.md Scan all MCP servers defined in the configuration file for reputation issues and update their blocking status. This example loads configurations, scans them, and prints the updated blocking status. ```python from mcp_gateway.config import load_config scanner = Scanner() servers = load_config("~/.cursor/mcp.json") updated_servers = scanner.scan_mcps_reputation(servers, "~/.cursor/mcp.json") for name, config in updated_servers.items(): status = config.get("blocked", "unknown") print(f"{name}: {status}") ``` -------------------------------- ### Create a Custom Guardrail Plugin Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/README.md Example of creating a custom guardrail plugin by extending the GuardrailPlugin class. Implement load, process_request, and process_response methods to define custom logic for request and response handling. ```python from mcp_gateway.plugins.base import GuardrailPlugin, PluginContext from mcp_gateway.plugins.manager import register_plugin @register_plugin class MyGuardrail(GuardrailPlugin): plugin_name = "my_plugin" def load(self, config=None): self.enabled = True def process_request(self, context: PluginContext): # Modify or return None to block return context.arguments def process_response(self, context: PluginContext): # Modify response return context.response ``` -------------------------------- ### UV Server Command Configuration Source: https://github.com/lasso-security/mcp-gateway/blob/main/_autodocs/configuration.md Configures a server to run using the UV package manager. This is useful for projects managed with UV. ```json { "command": "uv", "args": ["run", "--with", "package", "module_name"] } ``` -------------------------------- ### Build MCP Gateway Docker Image Source: https://github.com/lasso-security/mcp-gateway/blob/main/README.md Build the mcp-gateway Docker image. The image can be built with optional dependencies using the `INSTALL_EXTRAS` build argument. ```bash docker build -t mcp/gateway . ```