### ColabSessionProxy Example Source: https://context7.com/googlecolab/colab-mcp/llms.txt This Python script demonstrates the usage of ColabSessionProxy to manage the MCP proxy server lifecycle. It includes starting the proxy, mounting it to a FastMCP instance, and adding middleware for connection tracking. ```python import asyncio from fastmcp import FastMCP from colab_mcp.session import ColabSessionProxy async def main(): mcp = FastMCP(name="ColabMCP") session_proxy = ColabSessionProxy() # Start the proxy server and WebSocket listener await session_proxy.start_proxy_server() # Mount the proxy server to the main MCP instance mcp.mount(session_proxy.proxy_server) # Add middleware for connection state tracking for middleware in session_proxy.middleware: mcp.add_middleware(middleware) try: # Run the MCP server await mcp.run_async() finally: # Cleanup resources await session_proxy.cleanup() asyncio.run(main()) ``` -------------------------------- ### Configure colab-mcp with uvx Source: https://github.com/googlecolab/colab-mcp/blob/main/README.md Configure colab-mcp to be run using 'uvx' for package installation. This is useful for services that use a JSON-style configuration. ```json ... "mcpServers": { "colab-mcp": { "command": "uvx", "args": ["git+https://github.com/googlecolab/colab-mcp"], "timeout": 30000 } } ... ``` -------------------------------- ### Setup ColabProxyMiddleware Source: https://context7.com/googlecolab/colab-mcp/llms.txt Shows how to add ColabProxyMiddleware to an MCP instance to track Colab connection state and notify clients of tool list changes. The middleware automatically handles connection status and proxy information. ```python from colab_mcp.session import ColabProxyMiddleware, ColabProxyClient from fastmcp import FastMCP async def setup_middleware(mcp: FastMCP, proxy_client: ColabProxyClient): middleware = ColabProxyMiddleware(proxy_client) mcp.add_middleware(middleware) # The middleware automatically: # - Sets 'fe_connected' state on each message # - Sets 'proxy_token' and 'proxy_port' for connection info # - Sends tool_list_changed notification when connection state changes # - Handles the open_colab_browser_connection tool with connection waiting ``` -------------------------------- ### ColabProxyClient Example Source: https://context7.com/googlecolab/colab-mcp/llms.txt This Python script shows how to use ColabProxyClient to manage the MCP client connection to a Colab session. It includes a factory method for dynamic client selection and handles connection status checks. ```python import asyncio from colab_mcp.session import ColabProxyClient from colab_mcp.websocket_server import ColabWebSocketServer async def main(): async with ColabWebSocketServer() as wss: async with ColabProxyClient(wss) as proxy_client: # Check if connected to Colab if proxy_client.is_connected(): print("Connected to Colab session") client = proxy_client.client_factory() # Use the real MCP client else: print("Not connected, using stubbed client") client = proxy_client.client_factory() # Returns stubbed client for graceful degradation # Wait for connection with timeout await proxy_client.await_proxy_connection() if proxy_client.is_connected(): print("Connection established!") asyncio.run(main()) ``` -------------------------------- ### ColabWebSocketServer Example Source: https://context7.com/googlecolab/colab-mcp/llms.txt This Python script demonstrates how to use ColabWebSocketServer to handle secure WebSocket connections from Google Colab. It shows how to establish a connection, read messages, and send JSONRPC requests. ```python import asyncio from colab_mcp.websocket_server import ColabWebSocketServer async def main(): async with ColabWebSocketServer(host="localhost") as server: print(f"Server running on ws://localhost:{server.port}") print(f"Authentication token: {server.token}") # Wait for a connection from Colab await server.connection_live.wait() print("Colab session connected!") # Read messages from Colab message = await server.read_stream.receive() print(f"Received: {message}") # Send messages to Colab from mcp.types import JSONRPCRequest from mcp.shared.message import SessionMessage request = JSONRPCRequest( jsonrpc="2.0", id="1", method="execute", params={"code": "print('Hello from MCP!')"} ) await server.write_stream.send(SessionMessage(request)) asyncio.run(main()) ``` -------------------------------- ### Send and Receive JSON-RPC Messages Source: https://context7.com/googlecolab/colab-mcp/llms.txt Illustrates sending a JSON-RPC request from the server to a client and receiving a response. This example simulates a client connection and message exchange for MCP protocol communication. ```python import asyncio from colab_mcp.websocket_server import ColabWebSocketServer from mcp.types import JSONRPCRequest, JSONRPCResponse, JSONRPCMessage from mcp.shared.message import SessionMessage async def handle_messages(): async with ColabWebSocketServer() as server: # Simulate client connection (in real usage, Colab connects) import websockets client = await websockets.connect( f"ws://localhost:{server.port}?access_token={server.token}", origin="https://colab.google.com", subprotocols=["mcp"] ) # Send request from server to client request = JSONRPCRequest( jsonrpc="2.0", id="req-1", method="notebook/execute", params={"cell_id": "abc123"} ) await server.write_stream.send(SessionMessage(request)) # Client receives and responds msg_str = await client.recv() response = JSONRPCResponse( jsonrpc="2.0", id="req-1", result={"output": "Hello World"} ) await client.send(response.model_dump_json()) # Server receives the response received = await server.read_stream.receive() print(f"Server received: {received.message}") await client.close() asyncio.run(handle_messages()) ``` -------------------------------- ### Initialize and Use ColabTransport Source: https://context7.com/googlecolab/colab-mcp/llms.txt Demonstrates setting up ColabTransport to wrap WebSocket server streams for MCP client session communication. Ensure ColabWebSocketServer is running before connecting. ```python import asyncio from colab_mcp.session import ColabTransport from colab_mcp.websocket_server import ColabWebSocketServer async def main(): async with ColabWebSocketServer() as wss: transport = ColabTransport(wss) # Connect to a client session using the transport async with transport.connect_session() as session: # Session is now connected via WebSocket # Can be used for MCP protocol communication print(f"Session connected: {session}") asyncio.run(main()) ``` -------------------------------- ### Configure Git Hooks Source: https://github.com/googlecolab/colab-mcp/blob/main/README.md Set up Git hooks to automatically run repository presubmits. This ensures code quality and consistency before commits are finalized. ```shell git config core.hooksPath .githooks ``` -------------------------------- ### Configure colab-mcp with uv Source: https://github.com/googlecolab/colab-mcp/blob/main/README.md Configure colab-mcp to be run using 'uv' for direct execution. This configuration specifies the command, arguments, working directory, and timeout. ```json ... "mcpServers": { "colab-mcp": { "command": "uv", "args": ["run", "colab-mcp"], "cwd": "/path/to/github/colab-mcp", "timeout": 30000 } } ... ``` -------------------------------- ### Run colab-mcp CLI with Custom Log Directory Source: https://context7.com/googlecolab/colab-mcp/llms.txt The colab-mcp command-line interface supports custom log directory and proxy configurations. Use the --log flag to specify a custom directory for logs. ```bash # Run with default settings (proxy enabled, logs to temp directory) colab-mcp # Specify custom log directory colab-mcp --log /path/to/logs # Explicitly enable proxy (default behavior) colab-mcp --enable-proxy ``` -------------------------------- ### Configure colab-mcp as an MCP Server Source: https://context7.com/googlecolab/colab-mcp/llms.txt Configure colab-mcp within your client's configuration file to establish it as an MCP server. This JSON configuration specifies the command to run and its arguments. ```json { "mcpServers": { "colab-mcp": { "command": "uvx", "args": ["git+https://github.com/googlecolab/colab-mcp"], "timeout": 30000 } } } ``` -------------------------------- ### WebSocket Connection with Header Authentication Source: https://context7.com/googlecolab/colab-mcp/llms.txt Connects to a ColabWebSocketServer using a Bearer token in the Authorization header. Ensure the server is running and accessible. ```python import asyncio import websockets from colab_mcp.websocket_server import ColabWebSocketServer async def connect_with_header_auth(): async with ColabWebSocketServer() as server: # Method 1: Bearer token in Authorization header client = await websockets.connect( f"ws://localhost:{server.port}", origin="https://colab.google.com", subprotocols=["mcp"], additional_headers={"Authorization": f"Bearer {server.token}"} ) print("Connected with header auth") await client.close() asyncio.run(connect_with_header_auth()) ``` -------------------------------- ### WebSocket Connection with URL Authentication Source: https://context7.com/googlecolab/colab-mcp/llms.txt Connects to a ColabWebSocketServer using an access token in the URL query parameter. This method is an alternative to header-based authentication. ```python import asyncio import websockets from colab_mcp.websocket_server import ColabWebSocketServer async def connect_with_url_auth(): async with ColabWebSocketServer() as server: # Method 2: Token in URL query parameter client = await websockets.connect( f"ws://localhost:{server.port}?access_token={server.token}", origin="https://colab.google.com", subprotocols=["mcp"] ) print("Connected with URL auth") await client.close() asyncio.run(connect_with_url_auth()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.