import asyncio import json import re import time import gradio as gr import ollama import subprocess from mcp import ClientSession from mcp.client.sse import sse_client # --- 1. Setup Ollama (run once, uncomment if needed) --- def setup_ollama(): subprocess.run("apt-get update && apt-get install -y zstd", shell=True, check=True) subprocess.run("curl -fsSL https://ollama.com/install.sh | sh", shell=True, check=True) subprocess.Popen(["ollama", "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(5) subprocess.run(["ollama", "pull", "qwen3.5:0.8b"], check=True) setup_ollama() # Uncomment if needed SYSTEM_PROMPT_BASE = """You are Alex, a helpful AI assistant with access to external tools via MCP servers. RULES: 1. For general conversation (greetings, questions about yourself, small talk) — reply naturally in plain text. Do NOT call any tool. 2. Only call a tool when the user provides specific coordinates or explicitly asks for geospatial/environmental data. 3. When calling a tool, respond with ONLY this JSON block and nothing else: {"name": "exact_tool_name", "arguments": {"param1": value1}} 4. After receiving a tool result, summarise it clearly in plain English. Do not repeat the raw JSON. Your name is Alex. You were created to help with geospatial and environmental data analysis. Available tools are listed below. """ MCP_SERVER_URL = "https://test01t1-mcp-data.hf.space/gradio_api/mcp/sse" # --------------------------------------------------------------------------- # MCP helpers (async) # --------------------------------------------------------------------------- async def get_mcp_tools_async(server_url: str) -> list[dict]: try: async with sse_client(server_url) as (read_stream, write_stream): async with ClientSession(read_stream, write_stream) as session: await session.initialize() tools_result = await session.list_tools() return [ { "name": tool.name, "description": tool.description, "input_schema": tool.inputSchema, } for tool in tools_result.tools ] except Exception as e: print(f"Failed to fetch tools: {e}") return [] async def call_mcp_tool_async(server_url: str, tool_name: str, arguments: dict) -> str: try: async with sse_client(server_url) as (read_stream, write_stream): async with ClientSession(read_stream, write_stream) as session: await session.initialize() result = await session.call_tool(tool_name, arguments=arguments) if result.content: first = result.content[0] return first.text if hasattr(first, "text") else str(first) return "Tool returned no content." except Exception as e: return f"Error calling tool {tool_name}: {e}" def get_mcp_tools(server_url: str) -> list[dict]: return asyncio.run(get_mcp_tools_async(server_url)) def call_mcp_tool(server_url: str, tool_name: str, arguments: dict) -> str: return asyncio.run(call_mcp_tool_async(server_url, tool_name, arguments)) # --------------------------------------------------------------------------- # Clean raw MCP result — strip FileData blobs, keep only text lines # --------------------------------------------------------------------------- def clean_tool_result(raw: str) -> str: """ MCP results sometimes come back as a Python-repr list containing FileData dicts and plain strings mixed together. This function extracts only the human-readable text parts. """ try: items = eval(raw) # safe here: server-controlled data if isinstance(items, list): text_parts = [] for item in items: if isinstance(item, str): text_parts.append(item.strip()) elif isinstance(item, dict): # Skip FileData blobs; optionally surface the URL url = item.get("url", "") if url and not url.startswith("__"): text_parts.append(f"[image: {url}]") return "\n".join(p for p in text_parts if p) except Exception: pass # Fallback: strip obvious FileData noise with regex raw = re.sub( r"\{[^}]*'_type':\s*'gradio\.FileData'[^}]*\},?\s*", "", raw, flags=re.DOTALL, ) return raw.strip() # --------------------------------------------------------------------------- # Type coercion — fixes small-LLM bug of passing numbers as strings # --------------------------------------------------------------------------- def coerce_arguments(tool_call: dict, tools: list[dict]) -> dict: tool_name = tool_call.get("name") arguments = tool_call.get("arguments", {}) schema = next((t for t in tools if t["name"] == tool_name), None) if not schema: return arguments props = schema.get("input_schema", {}).get("properties", {}) coerced: dict = {} for key, value in arguments.items(): expected = props.get(key, {}).get("type", "string") try: if expected == "number" and isinstance(value, str): coerced[key] = float(value) elif expected == "integer" and isinstance(value, str): coerced[key] = int(value) elif expected == "boolean" and isinstance(value, str): coerced[key] = value.lower() in ("true", "1", "yes") else: coerced[key] = value except (ValueError, TypeError): coerced[key] = value return coerced # --------------------------------------------------------------------------- # Prompt / parsing helpers # --------------------------------------------------------------------------- def build_tool_prompt(tools: list[dict]) -> str: if not tools: return "\nNo tools available." lines = ["\nAvailable tools:"] for t in tools: lines.append(f"- {t['name']}: {t['description']}") props = t.get("input_schema", {}).get("properties", {}) if props: param_str = ", ".join( f"{k} ({v.get('type', 'any')})" for k, v in props.items() ) lines.append(f" Parameters: {param_str}") return "\n".join(lines) def extract_tool_call(text: str) -> dict | None: pattern = r"\s*(\{.*?\})\s*" match = re.search(pattern, text, re.DOTALL) if match: try: return json.loads(match.group(1)) except json.JSONDecodeError: return None return None def extract_text(content) -> str: if isinstance(content, str): return content if isinstance(content, list): return " ".join( block.get("text", "") for block in content if isinstance(block, dict) and block.get("type") == "text" ) return str(content) # --------------------------------------------------------------------------- # Main chat function # --------------------------------------------------------------------------- def chat_with_llm(message, history, show_thinking: bool, mcp_server_url: str): tools = get_mcp_tools(mcp_server_url) tool_prompt = build_tool_prompt(tools) full_system = SYSTEM_PROMPT_BASE + tool_prompt messages: list[dict] = [{"role": "system", "content": full_system}] for turn in history: if isinstance(turn, dict): role = turn.get("role") content = extract_text(turn.get("content", "")) if role and content: messages.append({"role": role, "content": content}) elif isinstance(turn, (list, tuple)) and len(turn) >= 2: user_msg = extract_text(turn[0]) if turn[0] else None bot_msg = extract_text(turn[1]) if turn[1] else None if user_msg: messages.append({"role": "user", "content": user_msg}) if bot_msg: messages.append({"role": "assistant", "content": bot_msg}) messages.append({"role": "user", "content": extract_text(message)}) max_iterations = 5 full_response = "" full_thinking = "" for _ in range(max_iterations): stream = ollama.chat( model="qwen3.5:0.8b", messages=messages, stream=True, think=show_thinking, options={"temperature": 0.6, "top_p": 0.9}, ) assistant_chunk = "" assistant_thinking = "" for chunk in stream: msg = chunk.get("message", {}) if msg.get("thinking"): assistant_thinking += msg["thinking"] if msg.get("content"): assistant_chunk += msg["content"] if show_thinking and assistant_thinking: yield ( f"šŸ’­ **Thinking:**\n{assistant_thinking}\n\n" f"šŸ“ **Answer:**\n{full_response}{assistant_chunk}" ) else: yield full_response + assistant_chunk messages.append({"role": "assistant", "content": assistant_chunk}) full_thinking += assistant_thinking tool_call = extract_tool_call(assistant_chunk) if not tool_call: full_response += assistant_chunk break tool_name = tool_call.get("name") if not tool_name: full_response += assistant_chunk break # Coerce types → call tool → clean result arguments = coerce_arguments(tool_call, tools) raw_result = call_mcp_tool(mcp_server_url, tool_name, arguments) clean_result = clean_tool_result(raw_result) # Feed clean result back so the LLM can summarise it messages.append( { "role": "system", "content": ( f"Tool '{tool_name}' returned the following data:\n{clean_result}\n\n" "Now summarise this result clearly for the user in plain English." ), } ) tool_block = ( f"\n\nšŸ”§ **Tool:** `{tool_name}` | " f"āš™ļø **Args:** `{json.dumps(arguments)}`\n\n" f"```\n{clean_result}\n```\n\n" ) full_response += assistant_chunk + tool_block yield full_response if show_thinking and full_thinking: yield ( f"šŸ’­ **Thinking:**\n{full_thinking}\n\n" f"šŸ“ **Answer:**\n{full_response}" ) else: yield full_response # --------------------------------------------------------------------------- # Gradio UI # --------------------------------------------------------------------------- demo = gr.ChatInterface( fn=chat_with_llm, title="šŸ¤– Alex — Geospatial AI Assistant", description=( "Powered by **qwen3:0.6b** via Ollama with live MCP tool access.\n" "Provide coordinates (lat, lon) to query terrain, land, meteorology, and more." ), additional_inputs=[ gr.Checkbox(label="Show thinking", value=True), gr.Textbox(label="MCP Server URL", value=MCP_SERVER_URL, visible=False), ], examples=[ ["Give me land data for 36.10, 10.45"], ["What is the terrain like at 33.89, 9.56?"], ["Show meteorology data for 37.27, 9.87"], ["Hi"], ["What is your name?"], ], cache_examples=False,) if __name__ == "__main__": demo.launch(share=True, mcp_server=True)