#!/usr/bin/env -S uv run
# /// script
# requires-python = ">=3.12"
# dependencies = [
#     "mcp~=1.30.0",
#     "hmr~=0.7.4",
#     "ipython~=9.17.1",
#     "logfire~=5.1.0",
#     "objprint~=0.3.0",
#     "uv~=0.7",
# ]
# ///

"""
IPython MCP Server using FastMCP
A Model Context Protocol server for programmatic IPython session management.
"""

from os import environ, getenv
from pathlib import Path
from site import addsitedir, getsitepackages
from sys import executable, path, platform, version_info

environ.setdefault("COLUMNS", "456")  # stdio server has no TTY, so get_terminal_size() falls back to a cramped 80x24 and wraps tracebacks/pretty far narrower than we render at
environ.setdefault("LINES", "123")

if parent := getenv("PARENT"):
    cwd = Path.cwd()
    for i in eval(parent):
        addsitedir(i)
    if project_site_packages := getenv("PROJECT_SITE_PACKAGES"):
        addsitedir(project_site_packages)
        venv_root = Path(project_site_packages).parents[1 if platform == "win32" else 2]
    else:
        venv_root = None

elif (venv_path := getenv("VIRTUAL_ENV")) and not Path(executable).is_relative_to(Path.cwd()):
    from subprocess import run
    from tempfile import TemporaryDirectory

    from uv import find_uv_bin

    def find_venv():
        current = Path.cwd()
        if (current / "pyvenv.cfg").is_file():
            return current

        for pyvenv_cfg in sorted(current.glob("*/pyvenv.cfg")) or sorted(current.glob("*/*/pyvenv.cfg")):
            return pyvenv_cfg.parent

        while current.parent != current:
            current = current.parent
            if (current / "pyvenv.cfg").is_file():
                return current
            for pyvenv_cfg in sorted(current.glob("*/pyvenv.cfg")):
                return pyvenv_cfg.parent

        return

    if venv_root := find_venv():
        rel_path = "Scripts/python.exe" if platform == "win32" else "bin/python"

        python_exe = venv_root / rel_path
        assert python_exe.is_file(), python_exe

        def get_python_version(exe):
            for line in (cfg := Path(exe).parent.parent / "pyvenv.cfg").open():
                if line.startswith(("version_info = ", "version = ")):
                    return line

            raise RuntimeError(f"Could not determine Python version for {cfg}")

        project_py_version = get_python_version(python_exe)
        current_py_version = get_python_version(executable)

        minor_version = project_py_version.split("=", 1)[-1].split(".")[1].strip()  # pyvenv.cfg lines trail \n
        site_packages = venv_root / ("Lib/site-packages" if platform == "win32" else f"lib/python3.{minor_version}/site-packages")
        assert site_packages.is_dir(), site_packages

        if project_py_version != current_py_version:
            with TemporaryDirectory("-venv", "ipython-mcp-") as temp_path:
                uv = find_uv_bin()
                run([uv, "venv", "-p", str(python_exe), "--seed", temp_path, "--link-mode", "symlink"], check=True)
                site_dirs = getsitepackages()
                new_env = {**environ, "PARENT": str(site_dirs), "VIRTUAL_ENV": temp_path, "UV_LINK_MODE": "symlink"}
                if str(site_packages) not in site_dirs:
                    new_env["PROJECT_SITE_PACKAGES"] = str(site_packages)
                try:
                    exit(run([uv, "run", "-p", str(Path(temp_path, rel_path)), "--active", __file__], env=new_env).returncode)  # noqa: PLR1722, PLW1510
                except KeyboardInterrupt:
                    exit(1)  # noqa: PLR1722
        else:
            addsitedir(str(site_packages))

else:
    venv_root = None

from ast import Import, ImportFrom, parse, walk
from asyncio import timeout as async_timeout
from asyncio.subprocess import PIPE, create_subprocess_shell
from collections.abc import Callable
from contextlib import contextmanager, redirect_stderr, redirect_stdout, suppress
from contextvars import ContextVar
from dis import get_instructions
from functools import cache, wraps
from inspect import isclass
from io import StringIO
from itertools import cycle
from linecache import getlines
from operator import call
from re import IGNORECASE, compile
from sys import _getframe, stderr
from types import CodeType
from typing import Any, TypedDict
from uuid import uuid4

from IPython.core.interactiveshell import InteractiveShell
from IPython.lib.pretty import pretty
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.exceptions import ToolError
from mcp.types import CallToolResult, TextContent, ToolAnnotations
from objprint import ObjPrint
from pydantic import Field
from reactivity.hmr import cache_across_reloads


class ExecutionResult(TypedDict):
    """Result of code execution in IPython session"""

    success: bool
    stdout: str
    stderr: str
    error: str | None
    result: Any
    note: str | None


type ImportSignature = tuple[str, str, str]  # (module, member, explicit_alias)

_redundant_imports: ContextVar[list[ImportSignature] | None] = ContextVar("ipython_mcp_redundant_imports", default=None)


def _format_import_hint(signatures: list[ImportSignature]) -> str | None:
    names = []
    for module, member, alias in signatures:
        name = f"{module}{'' if module.endswith('.') else '.'}{member}" if member else module
        names.append(f"{name} as {alias}" if alias else name)
    if not (names := list(dict.fromkeys(names))):
        return None
    quoted = [f"`{n}`" for n in names]
    if len(quoted) == 1:
        return f"{quoted[0]} has already been imported in this session — no need to re-import it."
    return f"{', '.join(quoted[:-1])} and {quoted[-1]} have already been imported in this session — no need to re-import them."


def _import_bindings(code, filename: str) -> dict[int, ImportSignature]:
    """Map STORE_NAME offsets to import signatures.

    AST retains explicit aliases; filename disambiguates otherwise equal code objects.
    """
    try:
        tree = parse("".join(getlines(filename)))
    except (SyntaxError, ValueError):
        return {}

    statements = {}
    for node in walk(tree):
        if not isinstance(node, (Import, ImportFrom)):
            continue
        bindings = []
        for name in node.names:
            if name.name == "*":
                continue
            if isinstance(node, Import):
                signature = (name.name, "", name.asname or "")
                bound = name.asname or name.name.split(".")[0]
            else:
                signature = ("." * node.level + (node.module or ""), name.name, name.asname or "")
                bound = name.asname or name.name
            bindings.append((bound, signature))
        statements[(node.lineno, node.end_lineno, node.col_offset, node.end_col_offset)] = cycle(bindings)  # CPython duplicates finally blocks.

    result = {}
    for instruction in get_instructions(code):
        if instruction.opname == "STORE_NAME" and (bindings := statements.get(instruction.positions)) is not None:
            binding = next(bindings, None)
            if binding is not None and binding[0] == instruction.argval:
                result[instruction.offset] = binding[1]
    return result


_cell_import_bindings: ContextVar[list[Callable[[CodeType, str], dict[int, ImportSignature]]] | None] = ContextVar("ipython_mcp_cell_import_bindings", default=None)


class HintingNamespace(dict):
    """Track successful import signatures per session."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._import_signatures: dict[str, set[ImportSignature]] = {}

    def clear(self):
        super().clear()
        self._import_signatures.clear()

    def __delitem__(self, key):
        super().__delitem__(key)
        # IPython reset deletes user keys individually instead of calling clear().
        self._import_signatures.pop(key, None)

    def __setitem__(self, key, value):
        signature = None
        # PyObject_SetItem is C, so frame 1 is the cell body itself; a non-cell frame binds elsewhere.
        if (redundant := _redundant_imports.get()) is not None and (caller := _getframe(1)).f_locals is self and (bindings := _cell_import_bindings.get()):
            signature = bindings[0](caller.f_code, caller.f_code.co_filename).get(caller.f_lasti)
            if signature is not None and signature in self._import_signatures.get(key, ()) and key in self and self[key] is value:
                redundant.append(signature)
        super().__setitem__(key, value)
        if signature is not None:
            self._import_signatures.setdefault(key, set()).add(signature)


class IPythonSession:
    """Manages an isolated IPython session"""

    def __init__(self):
        self.shell: InteractiveShell = InteractiveShell(user_ns=HintingNamespace())

        showtraceback = self.shell.showtraceback

        @wraps(showtraceback)
        def wrapper(*args, **kwargs):
            with redirect_stdout(stderr), redirect_stderr(stderr):
                return showtraceback(*args, **kwargs)

        self.shell.showtraceback = wrapper

        self.original_showtraceback = showtraceback

    @contextmanager
    def _capture_output(self):
        """Context manager to capture stdout and stderr"""
        with redirect_stdout(stdout := StringIO()), redirect_stderr(stderr := StringIO()):
            results: list[str] = []
            try:
                yield results
            finally:
                results[:] = [stdout.getvalue(), stderr.getvalue()]

    def format_exc(self):
        """Format an exception using IPython's traceback formatter"""

        with self._capture_output() as outputs:
            original_color_settings = self.shell.colors
            try:
                self.shell.colors = "nocolor"
                self.original_showtraceback()
            finally:
                self.shell.colors = original_color_settings
        return "\n".join(outputs).strip()

    async def run_cell_async(self, code: str) -> ExecutionResult:
        """Execute code asynchronously in the IPython session"""
        redundant: list[ImportSignature] = []
        token = _redundant_imports.set(redundant)
        bindings = cache(_import_bindings)
        cell_bindings: list[Callable[[CodeType, str], dict[int, ImportSignature]]] = [bindings]
        bindings_token = _cell_import_bindings.set(cell_bindings)
        try:
            with self._capture_output() as outputs:
                result = await self.shell.run_cell_async(code, transformed_cell=self.shell.transform_cell(code), store_history=True)
        finally:
            # Copied async contexts must not repopulate a completed cell's cache.
            cell_bindings.clear()
            bindings.cache_clear()
            _cell_import_bindings.reset(bindings_token)
            _redundant_imports.reset(token)

        stdout, stderr = outputs

        exc = result.error_before_exec or result.error_in_exec

        return {
            "success": result.success,
            "stdout": stdout,
            "stderr": stderr,
            "error": self.format_exc() if exc else None,
            "result": result.result,
            "note": _format_import_hint(redundant),
        }


@call
@cache_across_reloads
def sessions() -> dict[str, IPythonSession]:
    return {}


def _get_session(session_id: str):
    if session_id not in sessions:
        raise ToolError(f"[[ Session {session_id} not found! ]]")
    return sessions[session_id]


UUID_RE = compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", IGNORECASE)


def _is_uuid(text: str):
    return isinstance(text, str) and UUID_RE.fullmatch(text) is not None


def _shorten(text: str, max_length=70_000):
    if len(text) <= max_length + max_length // 10:  # 110%
        return text

    half = max_length // 2
    sep = " [...] " if "\n" not in text else "\n\n[...]\n\n"
    return text[:half] + sep + text[-half:]


def _as_xml(data: dict[str, str]):
    strings = {k: text if "\n" not in (text := v.strip()) else f"\n{text}\n" for k, v in data.items()}
    return "\n".join(f"<{k}>{_shorten(v)}</{k}>" for k, v in strings.items())


def _as_xml_blocks(data: dict[str, str]):
    strings = {k: text if "\n" not in (text := v.strip()) else f"\n{text}\n" for k, v in data.items()}
    return CallToolResult(content=[TextContent(text=f"<{k}>{_shorten(v)}</{k}>", type="text") for k, v in strings.items()])


class CustomObjectPrinter(ObjPrint):
    def _objstr(self, obj, memo, indent_level, cfg):
        cfg.attr_pattern = "(?!^__.*__$).*"
        if isclass(obj):
            return repr(obj)
        cls = type(obj)
        if cls.__repr__ is object.__repr__:
            return self._get_custom_object_str(obj, memo, indent_level, cfg)
        if callable(obj):
            return pretty(obj, verbose=True, max_width=320)
        return super()._objstr(obj, memo, indent_level, cfg)


_repr = CustomObjectPrinter().objstr

instructions = f"""
When you need to execute Python code programmatically, always prefer this IPython session over creating temporary files or using subprocess calls.
This provides a persistent, interactive Python environment with full access to IPython's features including magic commands.

Python 3.{version_info.minor} {f"in an **ephemeral** venv _inheriting from_ {venv_root}" if venv_root else f"at {executable}"}
{"Packages from the inherited project venv are already importable — no need to reinstall them.\n" if venv_root else ""}Installs land in the ephemeral venv only and won't pollute {"the project venv (or any other)" if venv_root else "any other venv"}.
"""
mcp = FastMCP("Python (IPython)", instructions)


@mcp.tool(title="Execute Python Code", annotations=ToolAnnotations(destructiveHint=False))
async def ipython_execute_code(
    code: str = Field(description="Python code to execute"),
    session_id: str | None = Field(None, description="Session ID returned by a previous call; leave unset on the very first call or when no ID was returned"),
    timeout_seconds: float | None = Field(300, le=300, description="Maximum seconds to wait, default and maximum 300; only async code is interruptible, so prefer top-level await over sync APIs. Set to null to disable timeout"),
):
    """
    Execute Python code in an IPython session with persistent state across calls.
    It's also common practice to write to a file first then %run it. All global state (variables, imports, etc.) will persist across calls within the same session.

    Features:
    - Variables persist between calls for incremental development
    - Import modules once, reuse throughout session
    - Magic commands for introspection, profiling, and environment management

    Session Management:
    - Reuse a session_id only if it was provided in an earlier response
    - Leave session_id unset on the first call or whenever no ID was returned previously

    Common Magic Commands:
    - Introspection: %whos (list vars), print? (signature), obj?? (source)
    - Performance: %timeit (benchmark), %prun (profile)
    - Environment: %env VAR=value (set), %cd /path (change dir)
    - Files: %run script.py args (execute), %%writefile file.py (save)

    Example input:
    data = [1, 2, 3]
    sum_data = sum(data)
    %whos  # View variables in session
    %timeit [x**2 for x in range(1000)]  # Benchmark
    """
    session_note = None
    if new_session := session_id is None:
        session_id = str(uuid4())
        session = sessions[session_id] = IPythonSession()
    elif session_id not in sessions:
        if _is_uuid(session_id):
            session = _get_session(session_id)
        session_id = str(uuid4())
        session = sessions[session_id] = IPythonSession()
        session_note = f"That session_id doesn't exist. I created a new session for you: {session_id}. Use this UUID next time instead of making one up."
        new_session = True
    else:
        session = sessions[session_id]

    async with async_timeout(timeout_seconds):
        result = await session.run_cell_async(code if isinstance(code, str) else f"%run {code}")

    if not result["success"]:
        assert result["error"] is not None
        if not result["stdout"].strip() and not result["stderr"].strip() and not new_session and not result["note"]:
            raise ToolError(result["error"])
        out = {"traceback": result["error"]}
        if new_session:
            out["session_id"] = session_note or session_id
        if stdout := result["stdout"].strip():
            out["stdout"] = stdout
        if stderr := result["stderr"].strip():
            out["stderr"] = stderr
        if note := result["note"]:
            out["note"] = note
        raise ToolError(_as_xml(out))

    out = {}

    if not result["stdout"].strip() and not result["stderr"].strip() and not result["note"]:
        if new_session:
            if session_note:
                return f"[[ execution successful, stdout/stderr empty, {session_note} ]]"
            return f"[[ execution successful, stdout/stderr empty, new IPython session created with ID: {session_id} ]]"
        if result["result"] is None:
            return "[[ execution successful, stdout/stderr empty ]]"
        else:
            return _repr(result["result"])
    if new_session:
        out["session_id"] = session_note or session_id
    if stdout := result["stdout"].strip():
        out["stdout"] = stdout
    if stderr := result["stderr"].strip():
        out["stderr"] = stderr
    if result["result"] is not None:
        out["return"] = _repr(result["result"])
    if note := result["note"]:
        out["note"] = note

    return _as_xml_blocks(out)


@mcp.tool(title="uv pip install", annotations=ToolAnnotations(destructiveHint=False))
async def uv_pip_install(args: list[str] = Field(default_factory=list, description="Arguments passed after `uv pip install`")):  # noqa: B008
    """
    Install PyPI packages into this temporary execution environment using `uv pip install`.

    It installs into the current execution environment (not the project environment), and installed packages are shared by all sessions.
    Always prefer this over raw calls to `%pip`.
    """

    from uv import find_uv_bin

    proc = await create_subprocess_shell(f"{find_uv_bin()} pip install {' '.join(args)}", stdout=PIPE, stderr=PIPE)
    stdout, stderr = (chunk.decode(errors="replace").strip() for chunk in await proc.communicate())
    out = {k: v for k, v in {"stdout": stdout, "stderr": stderr}.items() if v}
    if proc.returncode:
        out["exit_code"] = str(proc.returncode)
        raise ToolError(_as_xml(out))
    if venv_root:
        out["note"] = f"New packages can only be accessed in this MCP server and won't affect the project environment ({venv_root})."
    return _as_xml(out) or "[[ uv pip install successful, stdout/stderr empty ]]"


@mcp.tool(title="Reset IPython Session", annotations=ToolAnnotations(destructiveHint=False))
def ipython_clear_context(
    session_id: str,
    delete: bool = Field(False, description="Delete the session after clearing"),  # noqa: FBT001, FBT003
):
    """
    Clear an IPython session's namespace and reset its state.

    This will:
    - Remove all user-defined variables from the session
    - Clear execution history
    - Reset the namespace to a clean state
    - Keep the session alive (unless delete=True)

    Args:
        session_id: ID of the session to reset
        delete: If True, delete the entire session after clearing
    """
    session = _get_session(session_id)
    session.shell.reset(aggressive=True)

    if delete:
        del sessions[session_id]
        return f"Session {session_id} deleted"
    else:
        return f"Session {session_id} reset"


if LOGFIRE_TOKEN := getenv("LOGFIRE_TOKEN"):
    from threading import Thread
    from time import sleep

    FLAG = " --- instrumented --- "  # Avoid duplicate instrumentation

    def worker():
        if environ.get(FLAG):
            import logfire
        else:
            environ[FLAG] = "1"
            sleep(0.5)
            import logfire

            logfire.configure(scrubbing=False, token=LOGFIRE_TOKEN, console=False, service_name="ipython")
            logfire.instrument_mcp()

        for tool in mcp._tool_manager._tools.values():  # noqa: SLF001
            tool.fn = logfire.instrument(span_name=f"<<< {tool.name} >>>", record_return=True)(tool.fn)

    Thread(target=worker, daemon=True).start()

if __name__ == "__main__":
    cwd = Path.cwd()
    if not any(Path(i).is_dir() and cwd.samefile(i) for i in path):
        path.insert(0, str(cwd))
    with suppress(KeyboardInterrupt):
        mcp.run("stdio")
