### Run Example Configuration and Connect via Second Proxy Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/00-index.md Demonstrates how to run the MCP Proxy with an example configuration and how to connect a second instance to the running proxy. ```bash mcp-proxy --port 8080 --named-server-config config_example.json ``` ```bash mcp-proxy http://127.0.0.1:8080/sse ``` -------------------------------- ### Install mcp-proxy via PyPI with uv Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Recommended method for installing the stable version of mcp-proxy using the uv tool. ```bash uv tool install mcp-proxy ``` -------------------------------- ### Install latest mcp-proxy from GitHub Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Installs the latest development version of mcp-proxy directly from its GitHub repository. ```bash uv tool install git+https://github.com/sparfenjenyuk/mcp-proxy ``` -------------------------------- ### Example Server Definitions in JSON Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/04-configuration-loader.md Provides concrete examples of server configurations within a JSON file, showcasing different settings like command, arguments, environment variables, and enablement. ```json { "mcpServers": { "fetch": { "enabled": true, "command": "uvx", "args": ["mcp-server-fetch"], "transportType": "stdio" }, "github": { "enabled": true, "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxx..." }, "transportType": "stdio" }, "disabled_server": { "enabled": false, "command": "some-command" } } } ``` -------------------------------- ### Example Usage of StdioServerParameters Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/06-types-and-data-structures.md Demonstrates creating instances of StdioServerParameters for both default and named MCP server configurations. ```python from mcp.client.stdio import StdioServerParameters # Default server default_server = StdioServerParameters( command="uvx", args=["mcp-server-fetch"], env={"LOG_LEVEL": "info"}, cwd=None ) # Named server named_server = StdioServerParameters( command="npx", args=["-y", "@modelcontextprotocol/server-github"], env={ "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_xxx", "LOG_LEVEL": "info" }, cwd="/home/user/projects" ) ``` -------------------------------- ### Instantiating MCPServerSettings Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/02-mcp-server-module.md Example of how to create an instance of MCPServerSettings with custom configuration. Ensure all required fields like bind_host and port are provided. ```python from mcp_proxy.mcp_server import MCPServerSettings settings = MCPServerSettings( bind_host="0.0.0.0", port=8080, stateless=False, allow_origins=["https://example.com"], expose_headers=["mcp-session-id", "custom-header"], log_level="INFO" ) ``` -------------------------------- ### Start Multiple Named MCP Servers Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Starts the mcp-proxy server and configures multiple named servers ('fetch' and 'fetch2') to be proxied. Each named server is defined by a name and its command string. ```bash mcp-proxy --port=8080 --named-server fetch 'uvx mcp-server-fetch' --named-server fetch2 'uvx mcp-server-fetch' ``` -------------------------------- ### Start MCP Proxy with Named Server Configuration File Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Starts the mcp-proxy server using a JSON configuration file to define named servers. This is an alternative to using the `--named-server` argument for each server. ```bash mcp-proxy --port=8080 --named-server-config ./servers.json ``` -------------------------------- ### Example Usage of run_mcp_server Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/02-mcp-server-module.md Demonstrates how to configure and run the MCP server with default settings and a default stdio server. Ensure necessary imports are included. ```python from mcp.client.stdio import StdioServerParameters from mcp_proxy.mcp_server import MCPServerSettings, run_mcp_server import asyncio async def main(): settings = MCPServerSettings( bind_host="127.0.0.1", port=8080, allow_origins=["*"], ) default_server = StdioServerParameters( command="uvx", args=["mcp-server-fetch"], env={}, cwd=None, ) await run_mcp_server( mcp_settings=settings, default_server_params=default_server, ) asyncio.run(main()) ``` -------------------------------- ### Install mcp-proxy via PyPI with pipx Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Alternative method for installing the stable version of mcp-proxy using pipx. ```bash pipx install mcp-proxy ``` -------------------------------- ### Enable and Start MCP Proxy Systemd Service Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md Commands to reload the systemd daemon, enable the MCP Proxy service to start on boot, and start the service immediately. Also includes commands to check the service status and view logs. ```bash sudo systemctl daemon-reload sudo systemctl enable mcp-proxy sudo systemctl start mcp-proxy # Check status sudo systemctl status mcp-proxy sudo journalctl -u mcp-proxy -f ``` -------------------------------- ### Start Proxy with Local Server for Development Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md Starts the mcp-proxy in debug mode with a local server. This is typically run in one terminal to prepare for testing in others. ```bash # Terminal 1: Start proxy with local server mcp-proxy --port 8080 --debug uvx mcp-server-fetch ``` -------------------------------- ### Browser Client Request Example Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md An example of how a browser client can make a POST request to the MCP Proxy using the Fetch API. This demonstrates sending a JSON-RPC request. ```javascript const response = await fetch('http://localhost:8080/mcp/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }) }); const result = await response.json(); ``` -------------------------------- ### Example Usage of Configuration Loader Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/04-configuration-loader.md Demonstrates how to load server configurations using `load_named_server_configs_from_file` and access the loaded server parameters. Ensure the `servers.json` file exists and is correctly formatted. ```python from pathlib import Path from mcp_proxy.config_loader import load_named_server_configs_from_file # Load configuration config_path = Path("./servers.json") base_env = { "LOG_LEVEL": "info", "COMMON_VAR": "shared_value" } servers = load_named_server_configs_from_file(config_path, base_env) # Access a server if "fetch" in servers: fetch_server = servers["fetch"] print(f"Command: {fetch_server.command}") print(f"Args: {fetch_server.args}") print(f"Env: {fetch_server.env}") # Includes base_env + merged env ``` -------------------------------- ### CLI Usage Example: Load Servers from File Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/04-configuration-loader.md Illustrates the command-line usage for loading server configurations from a specified JSON file using the `mcp-proxy` tool. ```bash # Load servers from configuration file mcp-proxy --port 8080 --named-server-config ./servers.json ``` -------------------------------- ### Run mcp-server-fetch behind mcp-proxy over SSE Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Starts the mcp-server-fetch server, proxying it over SSE. This command should be run in the background. ```bash # Run the stdio server called mcp-server-fetch behind the proxy over SSE mcp-proxy --port=8080 uvx mcp-server-fetch & ``` -------------------------------- ### Setup Logging Configuration Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/01-main-entry-points.md Configures basicConfig with timestamped format and returns the root logger. Debug mode takes precedence over log level. ```python def _setup_logging(*, level: str, debug: bool) -> logging.Logger ``` -------------------------------- ### Start MCP Proxy with Custom Host and Port Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Starts the mcp-proxy server on a specific host (0.0.0.0) and port (8080), connecting to a local MCP server. This allows the proxy to be accessible from any network interface. ```bash mcp-proxy --host=0.0.0.0 --port=8080 uvx mcp-server-fetch ``` -------------------------------- ### Invalid Server Entry (Not Dictionary) Example Config Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Demonstrates a configuration where a server entry is not a dictionary, which will be logged as a warning and skipped. ```json { "mcpServers": { "server1": "not_a_dict" } } ``` -------------------------------- ### Setup Argument Parser Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/01-main-entry-points.md Instantiates the argument parser with all required and optional arguments, organized into logical groups for SSE/StreamableHTTP client options, stdio client options, and SSE server options. ```python def _setup_argument_parser() -> argparse.ArgumentParser ``` -------------------------------- ### Example JSON Configuration File Structure Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/04-configuration-loader.md Illustrates the expected JSON format for defining MCP servers, including command, arguments, environment variables, and enablement status. ```json { "mcpServers": { "server_name": { "command": "command_to_execute", "args": ["arg1", "arg2"], "env": { "ENV_KEY": "env_value" }, "enabled": true, "timeout": 60, "transportType": "stdio" } } } ``` -------------------------------- ### Invalid Args Type Example Config Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Presents a configuration where the 'args' field for a server is not a list, which will trigger a warning and cause the entry to be skipped. ```json { "mcpServers": { "server1": { "command": "echo", "args": "not_a_list" } } } ``` -------------------------------- ### Run MCP Proxy with Config File and Default Server Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md Combine named servers from a configuration file with a default server specified directly on the command line. Shows example URLs for both default and named servers. ```bash # Default + named servers from config mcp-proxy \ --port 8080 \ --named-server-config ./servers.json \ uvx mcp-server-fetch # URLs: # - http://localhost:8080/sse (default) # - http://localhost:8080/servers/fetch/sse (from config, named 'fetch') # - http://localhost:8080/servers/github/sse (from config, named 'github') ``` -------------------------------- ### Start MCP Proxy with Custom User Agent Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Starts the mcp-proxy server with a custom user agent for the proxied request. The `--` separator is crucial for distinguishing mcp-proxy arguments from the proxied server's arguments. ```bash mcp-proxy --port=8080 -- uvx mcp-server-fetch --user-agent=YourUserAgent ``` -------------------------------- ### Start Proxy for MCP Inspector Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md Starts the mcp-proxy, typically in one terminal, to be used by the MCP Inspector in another terminal. ```bash # Terminal 1: Start proxy mcp-proxy --port 8080 uvx mcp-server-fetch ``` -------------------------------- ### Missing Command Field Log Output Example Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Illustrates the log output when a named server configuration is missing the 'command' field, leading to a warning and the entry being skipped. ```log WARNING [timestamp] mcp_proxy.config_loader Named server 'server1' from config is missing 'command'. Skipping. ``` -------------------------------- ### MCP Proxy Log Format Example Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Illustrates the standard format for log messages, including level, timestamp, module, and message. ```text [I 2025-01-15 10:30:45.123 mcp_proxy.mcp_server] Setting up default server: uvx mcp-server-fetch [D 2025-01-15 10:30:45.234 mcp_proxy.proxy_server] Capabilities: adding Tools... ``` -------------------------------- ### Start MCP Proxy with Custom Port Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Starts the mcp-proxy server on a custom port (8080) and connects to a local MCP server. Use this to avoid port conflicts or use a preferred port. ```bash mcp-proxy --port=8080 uvx mcp-server-fetch ``` -------------------------------- ### Troubleshooting: Specify full path to mcp-proxy binary Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Use this JSON configuration when Claude Desktop cannot start the server due to an ENOENT error. It requires the full path to the mcp-proxy binary. ```json { "fetch": { "command": "/full/path/to/bin/mcp-proxy", "args": [ "http://localhost:8932/sse" ] } } ``` -------------------------------- ### Main CLI Entry Point Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/01-main-entry-points.md The `main` function serves as the primary entry point for the mcp-proxy CLI. It handles argument parsing, logging setup, and mode detection (SSE client or stdio server). Use this function when invoking mcp-proxy from the command line. ```python def main() -> None: pass ``` ```python # Typically invoked via CLI # mcp-proxy http://localhost:8080/sse # mcp-proxy --port 8080 -- uvx mcp-server-fetch if __name__ == "__main__": main() ``` -------------------------------- ### Example MCP Proxy Configuration Structure Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md This JSON structure shows the expected format for an MCP Proxy configuration file, including the 'mcpServers' key. ```json { "mcpServers": { "server_name": { ... } } } ``` -------------------------------- ### Manage Docker Compose Services Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md Commands to start, view logs, and stop services defined in a docker-compose.yml file. ```bash docker-compose up -d # Check logs docker-compose logs -f mcp-proxy # Stop docker-compose down ``` -------------------------------- ### MCP Proxy Configuration File Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Example JSON configuration file for mcp-proxy, defining named servers with commands, arguments, environment variables, and transport types. ```json { "mcpServers": { "fetch": { "enabled": true, "timeout": 60, "command": "uvx", "args": [ "mcp-server-fetch" ], "transportType": "stdio" }, "github": { "timeout": 60, "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-github" ], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "" }, "transportType": "stdio" } } } ``` -------------------------------- ### Example Log for Missing Capabilities Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md This log entry indicates that the proxy is attempting to add 'Tools' capabilities, but might not be logging for 'Prompts' if the remote server does not support them. This helps in debugging capability mismatches. ```log DEBUG [timestamp] mcp_proxy.proxy_server Capabilities: adding Tools... (but not logging for Prompts if remote doesn't support them) ``` -------------------------------- ### Environment Variable Merging Example Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/04-configuration-loader.md Demonstrates how server-specific environment variables are merged with a base environment. Server-specific variables override those in the base environment. ```python base_env = {"COMMON": "base", "OVERRIDE": "base_value"} server_env = {"OVERRIDE": "server_value", "SERVER_ONLY": "value"} # Resulting env (base_env copy, then updated with server_env) result_env = {"COMMON": "base", "OVERRIDE": "server_value", "SERVER_ONLY": "value"} ``` -------------------------------- ### Server Disabled Log Output Example Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Shows the log output when a named server is disabled in the configuration, resulting in an info message and the server being skipped. ```log INFO [timestamp] mcp_proxy.config_loader Named server 'disabled_server' from config is not enabled. Skipping. ``` -------------------------------- ### CLI Usage Example: Precedence of Config File Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/04-configuration-loader.md Demonstrates that the `--named-server-config` option takes precedence over `--named-server` CLI arguments, meaning arguments for named servers provided on the command line are ignored when a config file is used. ```bash # Configuration file takes precedence over CLI arguments # (--named-server arguments are ignored if --named-server-config is present) mcp-proxy --port 8080 \ --named-server-config ./servers.json \ --named-server cli_server "uvx mcp-server-fetch" ``` -------------------------------- ### Example JSON Configuration for Named Servers Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/00-index.md This JSON structure defines named servers, including their command, arguments, environment variables, and enabled status. It is used to load server configurations from a file. ```json { "mcpServers": { "server_name": { "command": "command_name", "args": ["arg1", "arg2"], "env": {"KEY": "value"}, "enabled": true } } } ``` -------------------------------- ### Invalid Args Type Log Output Example Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Shows the log output when a server's 'args' field is not a list, indicating an invalid type and that the entry is being skipped. ```log WARNING [timestamp] mcp_proxy.config_loader Named server 'server1' from config has invalid 'args' (must be a list). Skipping. ``` -------------------------------- ### Example Status Endpoint Response Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/06-types-and-data-structures.md An example of a JSON response from the status endpoint, showing typical values for API activity and server instances. ```json { "api_last_activity": "2025-01-15T10:30:45.123456+00:00", "server_instances": { "default": "configured", "fetch": "configured" } } ``` -------------------------------- ### Load Named Server Configurations from File Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/04-configuration-loader.md Demonstrates loading named server configurations from a JSON file. Includes error handling for FileNotFoundError, JSONDecodeError, and ValueError for incorrect formats. ```python import logging import json # Assume load_named_server_configs_from_file is defined elsewhere def load_named_server_configs_from_file(filepath, env): # Placeholder for actual implementation if filepath == "nonexistent.json": raise FileNotFoundError(f"File not found: {filepath}") elif filepath == "invalid.json": raise json.JSONDecodeError("Expecting value", "doc", 0) elif filepath == "wrong_format.json": raise ValueError("Missing mcpServers key") else: return {} logging.basicConfig(level=logging.INFO) # Missing file try: load_named_server_configs_from_file("nonexistent.json", {{}}) except FileNotFoundError as e: print(f"Config file not found: {e}") # Invalid JSON try: load_named_server_configs_from_file("invalid.json", {{}}) except json.JSONDecodeError as e: print(f"Invalid JSON: {e}") # Missing mcpServers key try: load_named_server_configs_from_file("wrong_format.json", {{}}) except ValueError as e: print(f"Invalid format: {e}") ``` -------------------------------- ### Start MCP Proxy with CORS Enabled Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Starts the mcp-proxy server with Cross-Origin Resource Sharing (CORS) enabled, allowing requests from any origin ('*') and exposing a custom header. This is useful for web applications interacting with the proxy. ```bash mcp-proxy --port=8080 --allow-origin='*' --expose-header Custom-Header uvx mcp-server-fetch ``` -------------------------------- ### Create MCP Server Settings Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/01-main-entry-points.md Creates an MCPServerSettings instance from parsed command-line arguments. Handles host, port, and expose header configurations. ```python def _create_mcp_settings(args_parsed: argparse.Namespace) -> MCPServerSettings: ``` -------------------------------- ### Deprecation Warning Logs Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Examples of deprecation warnings that may appear in MCP Proxy logs. ```text WARNING --named-server arguments are ignored when command_or_url is an HTTP/HTTPS URL (SSE/StreamableHTTP client mode). WARNING --named-server CLI arguments are ignored when --named-server-config is provided. ``` -------------------------------- ### MCP Proxy Configuration Loading Flow Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/09-architecture-and-flows.md Illustrates the sequence of operations for loading configuration, including argument parsing, server configuration, and settings creation. ```text Command Line Arguments │ ├──► _setup_argument_parser() │ ├──► parser.parse_args() │ │ │ └──► argparse.Namespace │ ├──► Argument Validation │ │ │ ├──► Is command_or_url an HTTP(S) URL? │ │ │ │ │ ├──YES: _handle_sse_client_mode() │ │ │ │ │ └──NO: Continue to stdio server mode │ │ │ ├──► _configure_default_server() │ │ │ └──► StdioServerParameters | None │ ├──► Load Named Servers │ │ │ ├──IF --named-server-config: │ │ │ │ │ ├──► _load_named_servers_from_config() │ │ │ │ │ ├──► load_named_server_configs_from_file() │ │ │ │ │ │ │ ├──► Read JSON file │ │ │ │ │ │ │ ├──► Validate format │ │ │ │ │ │ │ ├──► FOR each server in mcpServers: │ │ │ │ │ │ │ │ │ ├──► Check if enabled │ │ │ │ │ │ │ │ │ ├──► Validate command field │ │ │ │ │ │ │ │ │ ├──► Validate args type │ │ │ │ │ │ │ │ │ ├──► Merge environment variables │ │ │ │ │ │ │ │ │ └──► Create StdioServerParameters │ │ │ │ │ │ │ └──► dict[str, StdioServerParameters] │ │ │ │ │ │ └──ELIF --named-server: │ │ │ ├──► _configure_named_servers_from_cli() │ │ │ ├──► FOR each --named-server NAME CMD: │ │ │ │ │ ├──► shlex.split(CMD) │ │ │ │ │ ├──► Extract command and args │ │ │ │ │ └──► Create StdioServerParameters │ │ │ └──► dict[str, StdioServerParameters] │ ├──► _create_mcp_settings() │ │ │ └──► MCPServerSettings │ └──► run_mcp_server(settings, default, named) │ └──► (Start HTTP server with all configured servers) ``` -------------------------------- ### Dockerfile for MCP Proxy Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md A Dockerfile to build a custom mcp-proxy image, including installing additional tools like 'uv'. ```dockerfile FROM ghcr.io/sparfenyuk/mcp-proxy:v0.12.0 # Install additional tools RUN pip install --no-cache-dir uv ENV PATH="/usr/local/bin:$PATH" \ UV_PYTHON_PREFERENCE=only-system ENTRYPOINT ["catatonit", "--", "mcp-proxy"] ``` -------------------------------- ### Run MCP Proxy with Configuration File Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md Load server configurations from a JSON file using the `--named-server-config` flag. Disabled servers are automatically skipped. ```bash mcp-proxy --port 8080 --named-server-config ./servers.json # Disabled servers are skipped # Enabled servers are accessible at /servers/{name}/sse, /servers/{name}/mcp ``` -------------------------------- ### Route Processing for SSE Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/09-architecture-and-flows.md Details the route processing steps for an HTTP GET /sse request, from Starlette routing to the sse_transport.connect_sse call. ```mermaid HTTP GET /sse │ │ Starlette routing │ (find matching route) │ ├──► Route("/sse", handle_sse_instance) │ ├──► handle_sse_instance(request: Request) │ │ │ ├──► sse_transport.connect_sse(scope, receive, send) │ │ │ ├──► _update_global_activity() │ │ │ ├──► mcp_server_instance.run( │ │ read_stream, write_stream, │ │ init_options, stateless=...) │ │ │ └──► Return Response() │ ``` -------------------------------- ### Load Config File with Default Server Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/07-command-line-arguments.md Combine `--named-server-config` with a default server command. The configuration file takes precedence for its defined servers. ```bash mcp-proxy --port 8080 --named-server-config ./servers.json uvx mcp-server-fetch ``` -------------------------------- ### GET /sse Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/05-endpoints-and-routes.md Server-Sent Events (SSE) endpoint for MCP communication. It upgrades the connection to SSE for persistent bidirectional message streaming. ```APIDOC ## GET /sse ### Description SSE (Server-Sent Events) endpoint for MCP communication. Upgrades to SSE connection for MCP message streaming. Maintains persistent bidirectional communication channel. Client sends MCP requests as SSE events; server responds with results as SSE events. ### Method GET ### Endpoint /sse ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash curl -N http://localhost:8080/sse \ -H "Accept: text/event-stream" \ -H "Connection: upgrade" ``` ### Response #### Success Response (200) - **Content-Type**: text/event-stream; charset=utf-8 - **Headers**: Any custom expose headers configured #### Response Example None provided in source. ``` -------------------------------- ### mcp-proxy Command Line Arguments Help Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md This displays the usage information for the mcp-proxy command-line interface, outlining available options for client and server configurations, including transport, authentication, and environment variable handling. ```bash usage: mcp-proxy [-h] [--version] [-H KEY VALUE] [--transport {sse,streamablehttp}] [--verify-ssl [VALUE]] [--no-verify-ssl] [-e KEY VALUE] [--cwd CWD] [--client-id CLIENT_ID] [--client-secret CLIENT_SECRET] [--token-url TOKEN_URL] [--pass-environment | --no-pass-environment] [--log-level LEVEL] [--debug | --no-debug] [--named-server NAME COMMAND_STRING] [--named-server-config FILE_PATH] [--port PORT] [--host HOST] [--stateless | --no-stateless] [--sse-port SSE_PORT] [--sse-host SSE_HOST] [--allow-origin ALLOW_ORIGIN [ALLOW_ORIGIN ...]] [--expose-header HEADER] [command_or_url] [args ...] Start the MCP proxy in one of two possible modes: as a client or a server. positional arguments: command_or_url Command or URL to connect to. When a URL, will run an SSE/StreamableHTTP client. Otherwise, if --named-server is not used, this will be the command for the default stdio client. If --named-server is used, this argument is ignored for stdio mode unless no default server is desired. See corresponding options for more details. options: -h, --help show this help message and exit --version Show the version and exit SSE/StreamableHTTP client options: -H, --headers KEY VALUE Headers to pass to the SSE server. Can be used multiple times. --transport {sse,streamablehttp} The transport to use for the client. Default is SSE. --verify-ssl [VALUE] Control SSL verification when acting as a client. Use without a value to force verification, pass 'false' to disable, or provide a path to a PEM bundle. --no-verify-ssl Disable SSL verification (alias for --verify-ssl false). --client-id CLIENT_ID OAuth2 client ID for authentication --client-secret CLIENT_SECRET OAuth2 client secret for authentication --token-url TOKEN_URL OAuth2 token URL for authentication stdio client options: args Any extra arguments to the command to spawn the default server. Ignored if only named servers are defined. -e, --env KEY VALUE Environment variables used when spawning the default server. Can be used multiple times. For named servers, environment is inherited or passed via --pass-environment. --cwd CWD The working directory to use when spawning the default server process. Named servers inherit the proxy's CWD. --pass-environment, --no-pass-environment Pass through all environment variables when spawning all server processes. --log-level LEVEL Set the log level. Default is INFO. --debug, --no-debug Enable debug mode with detailed logging output. Equivalent to --log-level DEBUG. If both --debug and --log-level are provided, --debug takes precedence. --named-server NAME COMMAND_STRING Define a named stdio server. NAME is for the URL path /servers/NAME/. COMMAND_STRING is a single string with the command and its arguments (e.g., 'uvx mcp-server-fetch --timeout 10'). These servers inherit the proxy's CWD and environment from --pass-environment. --named-server-config FILE_PATH Path to a JSON configuration file for named stdio servers. If provided, this will be the exclusive source for named server definitions, and any --named-server CLI arguments will be ignored. ``` -------------------------------- ### Run MCP Inspector Against Proxy Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md Runs the MCP Inspector tool against a running mcp-proxy instance. This is usually performed in a separate terminal from where the proxy was started. ```bash # Terminal 2: Run MCP inspector against proxy mcp-inspector http://localhost:8080/sse ``` -------------------------------- ### Server Startup Informational Logs Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Common informational messages logged during MCP Proxy server startup. ```text INFO Starting SSE/StreamableHTTP client and stdio server INFO Configured default server: uvx mcp-server-fetch INFO Setting up default server: uvx mcp-server-fetch INFO Configured named server 'fetch': uvx mcp-server-fetch --timeout 60 INFO Serving MCP Servers via SSE: INFO - http://127.0.0.1:8080/sse ``` -------------------------------- ### MCP Proxy CORS Configuration Examples Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/05-endpoints-and-routes.md Configure CORS for the MCP Proxy by specifying allowed origins and exposed headers using command-line arguments. ```bash # Allow all origins mcp-proxy --port 8080 --allow-origin "*" uvx mcp-server-fetch # Allow specific origins mcp-proxy --port 8080 \ --allow-origin "https://example.com" \ --allow-origin "https://app.example.com" \ uvx mcp-server-fetch # Allow all origins with custom exposed headers mcp-proxy --port 8080 \ --allow-origin "*" \ --expose-header "Custom-Header" \ --expose-header "X-Request-ID" \ uvx mcp-server-fetch ``` -------------------------------- ### Load Named Server Configurations from File Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/04-configuration-loader.md Loads and parses server configurations from a specified JSON file. Requires a path to the config file and a base environment dictionary. Returns a dictionary mapping server names to their parameters. ```python def load_named_server_configs_from_file( config_file_path: str | Path, base_env: dict[str, str], ) -> dict[str, StdioServerParameters] ``` -------------------------------- ### GET /status Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/05-endpoints-and-routes.md Global health check and activity monitoring endpoint. It provides the last API activity timestamp and the status of configured server instances. ```APIDOC ## GET /status ### Description Global health check and activity monitoring. Provides the UTC timestamp of the last request to any endpoint and the status of configured server instances. ### Method GET ### Endpoint /status ### Parameters ### Request Body No request body is required. ### Response #### Success Response (200 OK) - **api_last_activity** (string (ISO 8601)) - UTC timestamp of last request to any endpoint - **server_instances** (object) - Map of server names to status string ("configured") #### Response Example ```json { "api_last_activity": "2025-01-15T10:30:45.123456+00:00", "server_instances": { "default": "configured", "fetch": "configured", "github": "configured" } } ``` ``` -------------------------------- ### MCPServerSettings Dataclass Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/00-index.md Defines the configuration settings for an MCP server, including host, port, CORS settings, and logging level. Used for server setup. ```python from dataclasses import dataclass from typing import Literal @dataclass class MCPServerSettings: bind_host: str # "127.0.0.1", "0.0.0.0" port: int # 8080, 0 for random stateless: bool = False # StreamableHTTP stateless mode allow_origins: list[str] | None = None # CORS origins expose_headers: list[str] = ["mcp-session-id"] # CORS expose headers log_level: Literal[...] = "INFO" # DEBUG, INFO, WARNING, ERROR, CRITICAL ``` -------------------------------- ### Claude Desktop MCP Server Configuration (Basic) Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md Configuration for ~/.claude/claude.json to set up mcp-proxy as an MCP server for Claude Desktop, specifying command, arguments, and environment variables. ```json { "mcpServers": { "my-mcp-proxy": { "command": "mcp-proxy", "args": [ "http://localhost:8080/sse" ], "env": { "API_ACCESS_TOKEN": "my-secret-token" } } } } ``` -------------------------------- ### Environment Variable Merging for Default Server Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/09-architecture-and-flows.md Shows how environment variables are combined from the base environment (if passed) and CLI arguments for a default server configuration. ```text Base Environment (if --pass-environment) │ ├──► os.environ (all current env vars) │ Merge with CLI --env │ ├──► --env KEY1 VALUE1 │ ├──► --env KEY2 VALUE2 │ Result: { "PATH": "/usr/bin:.", "HOME": "/home/user", ... "KEY1": "VALUE1", "KEY2": "VALUE2" } ``` -------------------------------- ### Configure Named Servers from CLI Arguments Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/01-main-entry-points.md Parses command strings from CLI arguments for named servers. Creates StdioServerParameters for each server using a copy of the base environment. Exits with status 1 if command strings are invalid. ```python def _configure_named_servers_from_cli( named_server_definitions: list[tuple[str, str]], base_env: dict[str, str], logger: logging.Logger, ) -> dict[str, StdioServerParameters] ``` -------------------------------- ### Display Help Message Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/07-command-line-arguments.md Use the --help or -h flags to display the help message and exit. ```bash mcp-proxy --help or mcp-proxy -h ``` ```bash mcp-proxy --help ``` -------------------------------- ### Create Standardized HTTPX AsyncClient Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/03-client-modules.md Use this factory function to create an httpx.AsyncClient with MCP defaults, including follow_redirects=True and a default timeout of 30 seconds. It also applies comprehensive logging and handles SSL verification based on the provided parameter. ```python from mcp_proxy.httpx_client import custom_httpx_client # Basic client client = custom_httpx_client() # With authentication from httpx_auth import OAuth2ClientCredentials auth = OAuth2ClientCredentials( client_id="id", client_secret="secret", token_url="https://auth.example.com/token" ) client = custom_httpx_client(auth=auth) # With custom CA bundle client = custom_httpx_client(verify_ssl="/path/to/ca-bundle.pem") # With disabled SSL verification (insecure, use with caution) client = custom_httpx_client(verify_ssl=False) ``` -------------------------------- ### Deprecated Client Entry Point Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/01-main-entry-points.md The `client` function is an alias for `main()`, intended for backwards compatibility with the `mcp-reverse-proxy` command. It is recommended to use `main()` directly. ```python def client() -> None: pass ``` -------------------------------- ### Shlex Parsing Error Example Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Handles cases where the COMMAND_STRING cannot be parsed by shlex, such as unclosed quotes. The proxy logs an exception and exits with code 1. Proper quoting is essential for shell metacharacters. ```bash mcp-proxy --named-server myserver "unclosed 'quote" --port 8080 ``` ```bash mcp-proxy --named-server myserver 'command "with" quotes' --port 8080 ``` -------------------------------- ### Proxy Server Handler Registration Flow Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/09-architecture-and-flows.md Illustrates the sequence of operations for creating and configuring a proxy server, including handler registration based on discovered capabilities. ```text create_proxy_server(remote_app: ClientSession) │ ├──► remote_app.initialize() │ │ │ └──► InitializeResult with capabilities │ ├──► Create server.Server(name=serverInfo.name) │ ├──► IF capabilities.prompts: │ │ │ ├──► Register ListPromptsRequest handler │ │ │ └──► Register GetPromptRequest handler │ ├──► IF capabilities.resources: │ │ │ ├──► Register ListResourcesRequest handler │ │ │ ├──► Register ListResourceTemplatesRequest handler │ │ │ ├──► Register ReadResourceRequest handler │ │ │ ├──► Register SubscribeRequest handler │ │ │ └──► Register UnsubscribeRequest handler │ ├──► IF capabilities.logging: │ │ │ └──► Register SetLevelRequest handler │ ├──► IF capabilities.tools: │ │ │ ├──► Register ListToolsRequest handler │ │ │ └──► Register CallToolRequest handler │ │ │ └──► Check for progressToken in metadata │ │ │ └──► Create progress_forwarder if present │ ├──► Register ProgressNotification handler │ ├──► Register CompleteRequest handler │ └──► Return configured Server instance ``` -------------------------------- ### CLI Integration for Named Server Configuration Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/04-configuration-loader.md Shows how the configuration loader is integrated into the main script (`__main__.py`) to handle named server configurations provided via a file path. ```python # From __main__.py # Assume args_parsed and base_env are defined elsewhere # def load_named_server_configs_from_file(filepath, env): # ... # if args_parsed.named_server_config: # named_stdio_params = load_named_server_configs_from_file( # args_parsed.named_server_config, # base_env, # ) ``` -------------------------------- ### Monitor Proxy Activity Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/05-endpoints-and-routes.md This Python script monitors proxy activity by periodically checking the 'api_last_activity' timestamp from the /status endpoint. It alerts if the proxy has been idle for more than 5 minutes. Ensure httpx and asyncio are installed. ```python import asyncio import httpx from datetime import datetime, timezone, timedelta async def monitor_proxy(): async with httpx.AsyncClient() as client: while True: status = await client.get("http://localhost:8080/status") last_activity = datetime.fromisoformat( status.json()["api_last_activity"] ) now = datetime.now(timezone.utc) idle_seconds = (now - last_activity).total_seconds() if idle_seconds > 300: # 5 minutes print(f"Proxy is idle: {idle_seconds}s") await asyncio.sleep(60) asyncio.run(monitor_proxy()) ``` -------------------------------- ### Load Named Servers from Configuration File Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/01-main-entry-points.md Loads named server configurations from a specified JSON file. Exits with status 1 on errors like file not found, invalid JSON, or incorrect format. Returns a dictionary of named server configurations. ```python def _load_named_servers_from_config( config_path: str, base_env: dict[str, str], logger: logging.Logger, ) -> dict[str, StdioServerParameters] ``` -------------------------------- ### Display Version Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/07-command-line-arguments.md Use the --version flag to display the current version of mcp-proxy and exit. ```bash mcp-proxy --version ``` ```bash # Output: mcp-proxy 0.12.0 ``` -------------------------------- ### Response Example for Tool Call Failure Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md This JSON structure represents a response from the remote server when a tool call fails. It includes a 'result' object with 'content' detailing the error and an 'isError' flag set to true. ```json { "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "Tool execution error: [error message]" } ], "isError": true } } ``` -------------------------------- ### Proxy with Custom Command and Arguments Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Run mcp-proxy with a custom command and its arguments, specifying the port. ```bash mcp-proxy --port 8080 -- your-command --arg1 value1 --arg2 value2 ``` -------------------------------- ### GET /servers/{name}/sse Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/05-endpoints-and-routes.md Server-Sent Events (SSE) endpoint for a named server. This allows multiple MCP servers to be exposed simultaneously at different paths, identical in function to the default server SSE endpoint. ```APIDOC ## GET /servers/{name}/sse ### Description SSE endpoint for named server. Identical to default server SSE endpoint but for a named server. Allows multiple MCP servers to be exposed simultaneously at different paths. ### Method GET ### Endpoint /servers/{name}/sse ### Parameters #### Path Parameters - **name** (string) - Required - The configured server name. ### Response #### Success Response (200) - (content type depends on SSE stream) #### Response Example (SSE stream example) ``` -------------------------------- ### Docker Compose Setup for Custom mcp-proxy Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md This Docker Compose configuration defines a service using a custom mcp-proxy Dockerfile. It sets network mode, restart policy, and port mapping, and specifies command-line arguments for the proxy. ```yaml services: mcp-proxy-custom: build: context: . dockerfile: mcp-proxy.Dockerfile network_mode: host restart: unless-stopped ports: - 8096:8096 command: "--pass-environment --port=8096 --sse-host 0.0.0.0 uvx mcp-server-fetch" ``` -------------------------------- ### Configure Default Stdio Server Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/01-main-entry-points.md Checks if the command is a local command and configures StdioServerParameters with merged environment variables and command arguments. Logs configuration details. Returns server parameters if applicable, otherwise None. ```python def _configure_default_server( args_parsed: argparse.Namespace, base_env: dict[str, str], logger: logging.Logger, ) -> StdioServerParameters | None ``` -------------------------------- ### SSL Certificate Verification Failed Fix Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Addresses SSL certificate verification failures for remote HTTPS servers when the --no-verify-ssl flag is not set. Provides examples for development with self-signed certificates and corporate environments with custom CA bundles. ```bash # Development with self-signed cert mcp-proxy --no-verify-ssl https://dev.local/sse ``` ```bash # Corporate environment with custom CA mcp-proxy --verify-ssl /etc/ssl/certs/corporate-ca.pem https://internal.example.com/sse ``` -------------------------------- ### Create MCPServerSettings from Arguments Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/06-types-and-data-structures.md Illustrates the creation of an MCPServerSettings object by parsing command-line arguments. Handles default values and conditional logic for settings like log level and CORS origins. ```python def _create_mcp_settings(args_parsed: argparse.Namespace) -> MCPServerSettings: expose_headers = ( list(DEFAULT_EXPOSE_HEADERS) if not args_parsed.expose_headers else list(args_parsed.expose_headers) ) return MCPServerSettings( bind_host=args_parsed.host if args_parsed.host is not None else args_parsed.sse_host, port=args_parsed.port if args_parsed.port is not None else args_parsed.sse_port, stateless=args_parsed.stateless, allow_origins=args_parsed.allow_origin if len(args_parsed.allow_origin) > 0 else None, expose_headers=expose_headers, log_level="DEBUG" if args_parsed.debug else args_parsed.log_level, ) ``` -------------------------------- ### Configure Working Directory for Server Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/10-usage-examples.md Set the working directory for the spawned server process. This is useful when your server expects to be run from a specific directory. ```bash # Run server in specific directory mcp-proxy \ --cwd /home/user/workspace \ --port 8080 \ python my_mcp_server.py ``` ```bash # With relative paths mcp-proxy \ --cwd ./servers/fetch \ --port 8080 \ mcp-server ``` -------------------------------- ### Configure OAuth2 Client Credentials Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/07-command-line-arguments.md Use --client-id, --client-secret, and --token-url to enable OAuth2 Client Credentials flow for authentication. All three must be provided. ```bash --client-id CLIENT_ID --client-secret CLIENT_SECRET --token-url TOKEN_URL ``` ```bash # OAuth2 authentication mcp-proxy \ --client-id "my_client_id" \ --client-secret "my_secret" \ --token-url "https://auth.example.com/oauth/token" \ https://api.example.com/sse ``` ```bash # OAuth2 with other options mcp-proxy \ --transport streamablehttp \ --client-id "client123" \ --client-secret "secret456" \ --token-url "https://auth.internal/token" \ https://internal-api/mcp ``` -------------------------------- ### stdio Client Options Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/06-types-and-data-structures.md Attributes for configuring stdio clients, covering command execution, trailing arguments, environment variables, working directory, and logging. ```python args_parsed.command_or_url: str | None # positional arg args_parsed.args: list[str] # trailing args after -- args_parsed.env: list[tuple[str, str]] # --env KEY VALUE args_parsed.cwd: str | None # --cwd args_parsed.pass_environment: bool # --pass-environment args_parsed.log_level: str # --log-level (default "INFO") args_parsed.debug: bool # --debug args_parsed.named_server_definitions: list[tuple[str, str]] # --named-server NAME CMD args_parsed.named_server_config: str | None # --named-server-config PATH ``` -------------------------------- ### Expose Local Server to Network Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/00-index.md Use this command to expose a local server to the network, making it accessible from other devices. It sets the host to all interfaces and specifies the port and log level. ```bash mcp-proxy --host 0.0.0.0 --port 3000 --pass-environment \ --log-level INFO \ uvx mcp-server-fetch ``` -------------------------------- ### Verify File Existence Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/_autodocs/08-error-handling.md Use the 'ls -la' command to verify if a configuration file exists at the specified path. ```bash ls -la path/to/config.json ``` -------------------------------- ### Proxy with Environment Variables Source: https://github.com/sparfenyuk/mcp-proxy/blob/main/README.md Run mcp-proxy with a custom command, specifying environment variables using -e. ```bash mcp-proxy your-command --port 8080 -e KEY VALUE -e ANOTHER_KEY ANOTHER_VALUE ```