Spaces:
Configuration error
Configuration error
Upload src/mcp_stdio.py with huggingface_hub
Browse files26 unmodified lines27282930313228 unmodified lines616263646566676869707172737426 unmodified linessys.stdout.write(line + "\n")sys.stdout.flush()def handle(req):method = req.get("method", "")req_id = req.get("id")28 unmodified linesname = params.get("name")args = params.get("arguments") or {}try:r = requests.post(f"{BASE}/mcp/tools",headers=headers(),json={"name": name, "arguments": args},timeout=30)result = r.json()# MCP expects content arrayif "content" not in result:result = {"content": [{"type": "text", "text": json.dumps(result)}]}send({"jsonrpc": "2.0", "id": req_id, "result": result})except Exception as e:send({"jsonrpc": "2.0", "id": req_id,26 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927028 unmodified lines29930030130230330430530630730830931031131231331431526 unmodified linessys.stdout.write(line + "\n")sys.stdout.flush()def perform_antigravity_sync_local(args):import osimport jsonimport globimport reimport requestsmode = args.get("mode") or "current_session"current_conversation_id = args.get("currentConversationId")current_folder = args.get("currentFolder")brain_dir = os.path.join(os.path.expanduser("~"), ".gemini", "antigravity", "brain")if not os.path.exists(brain_dir):return {"content": [{"type": "text", "text": json.dumps({"success": False,"syncedSessions": [],"observationsAdded": 0,"error": f"Brain directory not found at {brain_dir}"})}]}pattern = os.path.join(brain_dir, "*", ".system_generated", "logs", "transcript.jsonl")files = glob.glob(pattern)if not files:return {"content": [{"type": "text", "text": json.dumps({"success": True,"syncedSessions": [],"observationsAdded": 0})}]}conversations = []for fpath in files:try:mtime = os.path.getmtime(fpath)convo_id = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(fpath))))conversations.append({"id": convo_id,"transcriptPath": fpath,"mtime": mtime})except Exception:passif not conversations:return {"content": [{"type": "text", "text": json.dumps({"success": True,"syncedSessions": [],"observationsAdded": 0})}]}conversations.sort(key=lambda x: x["mtime"], reverse=True)targets = []if mode == "current_session":if current_conversation_id:match = next((c for c in conversations if c["id"] == current_conversation_id), None)if match:targets = [match]else:targets = [conversations[0]]elif mode == "current_folder":target_folder = current_folder if current_folder else ""if not target_folder:target_folder = os.getcwd()target_folder_norm = target_folder.replace("\\", "/").lower().strip()for convo in conversations:try:with open(convo["transcriptPath"], "r", encoding="utf-8") as tf:text = tf.read().lower()text_norm = text.replace("\\/", "/").replace("\\\\", "/")if target_folder_norm in text_norm:targets.append(convo)except Exception:passelif mode == "all":targets = conversationselse:return {"content": [{"type": "text", "text": json.dumps({"success": False,"syncedSessions": [],"observationsAdded": 0,"error": f"Invalid mode: {mode}"})}]}if not targets:return {"content": [{"type": "text", "text": json.dumps({"success": True,"syncedSessions": [],"observationsAdded": 0})}]}synced_sessions = []observations_added = 0headers_dict = headers()for convo in targets:convo_id = convo["id"]tpath = convo["transcriptPath"]session_id = f"antigravity_{convo_id[:18].replace('-', '_')}"project_path = Nonetry:with open(tpath, "r", encoding="utf-8") as tf:first_line = tf.readline()if first_line:step = json.loads(first_line)match = re.search(r"\[([^\]]+)\]\s*->\s*\[([^\]]+)\]", step.get("content", ""))if match:project_path = match.group(2)except Exception:passif not project_path:project_path = os.getcwd()turns = []current_prompt = Nonecurrent_timestamp = Nonetry:with open(tpath, "r", encoding="utf-8") as tf:for line in tf:if not line.strip():continuetry:step = json.loads(line)step_type = step.get("type")if step_type == "USER_INPUT":p_text = step.get("content", "")if "<USER_REQUEST>" in p_text:parts = p_text.split("<USER_REQUEST>")if len(parts) > 1:p_text = parts[1]if "</USER_REQUEST>" in p_text:p_text = p_text.split("</USER_REQUEST>")[0]current_prompt = p_text.strip()current_timestamp = step.get("created_at")elif step_type == "PLANNER_RESPONSE" and current_prompt:ts = current_timestamp or step.get("created_at")if not ts:import datetimets = datetime.datetime.utcnow().isoformat() + "Z"turns.append({"prompt": current_prompt,"response": step.get("content", ""),"timestamp": ts})current_prompt = Nonecurrent_timestamp = Noneexcept Exception:passexcept Exception:continueif not turns:continueexisting_inputs = set()try:r = requests.get(f"{BASE}/observations?sessionId={session_id}", headers=headers_dict, timeout=10)if r.status_code == 200:obs_list = r.json().get("observations", [])for obs in obs_list:tool_input = obs.get("toolInput") or (obs.get("raw") or {}).get("tool_input")if tool_input:existing_inputs.add(tool_input.strip())except Exception:passtry:sess_check = requests.get(f"{BASE}/sessions", headers=headers_dict, timeout=5)session_exists = Falseif sess_check.status_code == 200:sessions_list = sess_check.json().get("sessions", [])session_exists = any(s.get("id") == session_id for s in sessions_list)if not session_exists:session_payload = {"sessionId": session_id,"project": project_path,"cwd": project_path,"title": f"Antigravity Pair Programming ({convo_id[:8]})","agentId": "antigravity"}requests.post(f"{BASE}/session/start", headers=headers_dict, json=session_payload, timeout=10)except Exception:passconvo_synced = Falsefor turn in turns:prompt = turn["prompt"]if prompt.strip() in existing_inputs:continuepayload = {"sessionId": session_id,"project": project_path,"cwd": project_path,"hookType": "post_tool_use","timestamp": turn["timestamp"],"agentId": "antigravity","data": {"tool_name": "conversation","tool_input": prompt,"tool_output": turn["response"],}}try:requests.post(f"{BASE}/observe", headers=headers_dict, json=payload, timeout=10)observations_added += 1convo_synced = Trueexcept Exception:passif convo_synced:synced_sessions.append(convo_id)return {"content": [{"type": "text", "text": json.dumps({"success": True,"syncedSessions": synced_sessions,"observationsAdded": observations_added})}]}def handle(req):method = req.get("method", "")req_id = req.get("id")28 unmodified linesname = params.get("name")args = params.get("arguments") or {}try:if name == "memory_antigravity_sync":result = perform_antigravity_sync_local(args)else:r = requests.post(f"{BASE}/mcp/tools",headers=headers(),json={"name": name, "arguments": args},timeout=30)result = r.json()# MCP expects content arrayif "content" not in result:result = {"content": [{"type": "text", "text": json.dumps(result)}]}send({"jsonrpc": "2.0", "id": req_id, "result": result})except Exception as e:send({"jsonrpc": "2.0", "id": req_id,
src/mcp_stdio.py+249-8