MCP Server

import logging from typing import Optional from mcp.server.fastmcp import FastMCP from decouple import config from browser_use import Agent, BrowserConfig, Browser from langchain_openai import ChatOpenAI # Configure logging logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger(__name__) # Load your API keys or other environment variables via python-decouple. OPENAI_API_KEY = config("OPENAI_API_KEY") # Initialize the MCP server with a name (here "browser") mcp = FastMCP("browser") config = BrowserConfig( headless=True, ) browser = Browser(config=config) @mcp.tool() async def run_browser_task(task: str) -> str: """ Run a browser automation task using browser‑use. Args: task: A string describing the browser automation command to execute. Returns: A string with the result of executing the task. """ logger.info(f"🌐 Running browser task: {task}") try: agent = Agent(task=task, llm=ChatOpenAI(model="gpt-4o-mini"), browser=browser) result = await agent.run() # Log the result structure to understand what we're working with logger.debug(f"Result type: {type(result)}") logger.debug(f"Result content: {result}") # Handle the AgentHistoryList object correctly # If result is directly usable as a string, convert it if hasattr(result, "content"): response = result.content # If result is a list-like object, get the last item elif hasattr(result, "__getitem__") and len(result) > 0: last_result = result[-1] if hasattr(last_result, "extracted_content"): response = last_result.extracted_content elif hasattr(last_result, "content"): response = last_result.content else: response = str(last_result) else: # Fallback to string representation response = str(result) logger.info(f"✅ Browser task completed: {response[:100]}...") return response except Exception as e: error_msg = f"Failed to run browser task: {str(e)}" logger.error(f"❌ {error_msg}") return error_msg if __name__ == "__main__": logger.info("🚀 Starting MCP browser server") mcp.run(transport="sse")