Buckets:

download
raw
6.16 kB
"""
IP Tracker MCP Server – tracks who visits the Zen Terminal.
Reads the connection log, resolves IP geo info, and exposes tools
for the AI to check who is accessing the terminal.
"""
import json
import os
import subprocess
import time
from datetime import datetime, timedelta
from pathlib import Path
import httpx
from mcp.server.fastmcp import FastMCP
LOG_FILE = Path(os.environ.get("TERMINAL_LOG", "logs/terminal_connections.log"))
CACHE_FILE = Path("/tmp/obscura_ip_cache.json")
mcp = FastMCP("ip-tracker", instructions="Track visitor IPs connecting to the Zen Terminal.")
def _read_log(last_minutes: int = 60) -> list[dict]:
if not LOG_FILE.exists():
return []
entries = []
cutoff = datetime.now() - timedelta(minutes=last_minutes)
with open(LOG_FILE) as f:
for line in f:
line = line.strip()
if not line:
continue
try:
ts_str = line[1:20]
ts = datetime.strptime(ts_str, "%Y-%m-%d %H:%M:%S")
if ts < cutoff:
continue
rest = line[22:]
parts = rest.split()
entry = {"timestamp": ts_str, "raw": rest}
for p in parts:
if "=" in p:
k, v = p.split("=", 1)
entry[k] = v
entries.append(entry)
except (ValueError, IndexError):
entries.append({"raw": line})
return entries
def _resolve_ip(ip: str) -> dict:
if ip in ("127.0.0.1", "::1", "localhost", "unknown"):
return {"ip": ip, "type": "local"}
if CACHE_FILE.exists():
cache = json.loads(CACHE_FILE.read_text())
if ip in cache:
return cache[ip]
try:
r = httpx.get(f"http://ip-api.com/json/{ip}", timeout=5)
if r.status_code == 200:
data = r.json()
result = {
"ip": ip,
"country": data.get("country", "?"),
"region": data.get("regionName", "?"),
"city": data.get("city", "?"),
"isp": data.get("isp", "?"),
"org": data.get("org", "?"),
"type": "remote",
}
cache = json.loads(CACHE_FILE.read_text()) if CACHE_FILE.exists() else {}
cache[ip] = result
CACHE_FILE.write_text(json.dumps(cache, indent=2))
return result
except Exception:
pass
return {"ip": ip, "type": "unknown"}
def _my_public_ip() -> str:
for url in ("https://ifconfig.me/ip", "https://api.ipify.org", "https://icanhazip.com"):
try:
r = httpx.get(url, timeout=5)
ip = r.text.strip()
if ip and not ip.startswith("<"):
return ip
except Exception:
continue
return "unreachable"
@mcp.resource("tracker://status")
async def tracker_status() -> str:
"""Tracker status and log file info."""
return json.dumps(
{
"log_file": str(LOG_FILE),
"log_exists": LOG_FILE.exists(),
"log_size": LOG_FILE.stat().st_size if LOG_FILE.exists() else 0,
"public_ip": _my_public_ip(),
}
)
@mcp.tool()
def my_public_ip() -> str:
"""Get the public IP of this server via ifconfig.me."""
ip = _my_public_ip()
info = _resolve_ip(ip)
ip_type = "IPv4" if "." in ip else "IPv6" if ":" in ip else "unknown"
return json.dumps({"status": "ok", "public_ip": ip, "ip_version": ip_type, "details": info})
@mcp.tool()
def check_visitors(minutes: int = 60) -> str:
"""List everyone who connected to the terminal in the last N minutes."""
entries = _read_log(minutes)
if not entries:
return json.dumps({"status": "ok", "visitors": [], "count": 0})
unique_ips = {}
for e in entries:
ip = e.get("ip", e.get("raw", "").split()[1] if " " in e.get("raw", "") else "?")
if ip not in unique_ips:
unique_ips[ip] = {"first_seen": e["timestamp"], "events": []}
unique_ips[ip]["events"].append(e.get("raw", ""))
visitors = []
for ip, data in unique_ips.items():
info = _resolve_ip(ip)
ip_type = "IPv4" if "." in ip else "IPv6" if ":" in ip else "unknown"
visitors.append(
{
"ip": ip,
"ip_version": ip_type,
"location": f"{info.get('city', '?')}, {info.get('country', '?')}",
"isp": info.get("isp", info.get("type", "?")),
"first_seen": data["first_seen"],
"event_count": len(data["events"]),
}
)
return json.dumps(
{
"status": "ok",
"my_ip": _my_public_ip(),
"visitors": sorted(visitors, key=lambda v: v["first_seen"], reverse=True),
"count": len(visitors),
}
)
@mcp.tool()
def resolve_ip(ip: str) -> str:
"""Resolve an IP address to location details."""
info = _resolve_ip(ip)
return json.dumps({"status": "ok", "ip": ip, "details": info})
@mcp.tool()
def alert_new_visitor(webhook_url: str = "") -> str:
"""Check for new visitors since last check and optionally send webhook."""
last_check = Path("/tmp/obscura_last_check.txt")
last_ts = last_check.read_text().strip() if last_check.exists() else ""
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
entries = _read_log(1440)
new_visitors = []
for e in entries:
if e["timestamp"] > last_ts:
ip = e.get("ip", "?")
info = _resolve_ip(ip)
new_visitors.append(
{
"ip": ip,
"location": f"{info.get('city', '?')}, {info.get('country', '?')}",
"time": e["timestamp"],
}
)
last_check.write_text(now)
return json.dumps(
{
"status": "ok",
"new_visitors_since_last_check": len(new_visitors),
"visitors": new_visitors,
}
)
def main():
mcp.run()
if __name__ == "__main__":
main()

Xet Storage Details

Size:
6.16 kB
·
Xet hash:
6ca18aa5d4d236eb68504561df4a788bef4216d75d59a44c2eb220f59f755db4

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.