import os from dotenv import load_dotenv import gradio as gr from huggingface_hub import InferenceClient # 1. Load environment variables (so os.getenv sees HUGGINGFACE_API_TOKEN) load_dotenv() # 2. MCP & agent imports from smolagents import InferenceClientModel, CodeAgent, MCPClient, HfApiModel MPC_server = "https://abidlabs-mcp-tool-http.hf.space/gradio_api/mcp/sse" # MPC_server = "https://augustosouza-mcp-sentiment-server.hf.space/gradio_api/mcp/sse" try: # 3. Connect to a remote MCP Server over SSE # This URL hosts a collection of MCP tools on Hugging Face Spaces. mcp_client = MCPClient( {"url": MPC_server} ) # 4. Fetch the list of available tools from that server; literally “What tools does that server offer?” # Each tool has a name, description, and a callable interface. tools = mcp_client.get_tools() print(f"Here we are printing the tools fetched from the MCP Server:\n {tools[0].name}") # 5. Instantiate an inference model that will *drive* the agent: # - It uses your Hugging Face token for billing/auth. # - You can swap in any HF-hosted model by name or settings. model = InferenceClientModel(token=os.getenv("HUGGINGFACE_API_TOKEN")) # Qwen/Qwen2.5-Coder-32B-Instruct LLM # 6. Create a simple CodeAgent that: # - Knows about all `tools` you fetched # - Uses `model` to decide *which* tool to call, and *with what inputs* agent = CodeAgent( tools=[*tools], model=model, additional_authorized_imports=["json", "ast", "urllib", "base64"] # if your tools need it ) # 7. Build the Gradio chat interface around that agent: demo = gr.ChatInterface( fn=lambda message, history: str(agent.run(message)), type="messages", examples=["Write something below. This is a basic AI application powered with MCP. Currently integrated this app is the Qwen/Qwen2.5-Coder-32B-Instruct LLM and has its capabilities extended with 4 specifics Tools from the https://huggingface.co/spaces/abidlabs/mcp-tool-http/blob/main/app.py MCP server"], title="Agent with MCP Tools", description="This is a simple agent that uses MCP tools to answer questions." ) # 8. Launch both: # - A Gradio web UI at http://127.0.0.1:7860 # - An MCP server endpoint under `/gradio_api/mcp/sse` (for other clients) demo.launch() finally: # 9. Clean shutdown of the MCP client’s SSE/WebSocket connection. mcp_client.disconnect()