"""MCP server helpers for ProxAgent."""


def create_memory_server(agent):
    """Create an MCP server with a save_learning tool.

    The tool writes to _proxagent_memories via agent.save_memory().

    Usage:
        agent = ProxAgent("my-agent", ...).fetch()
        memory_server = create_memory_server(agent)
        # pass to ClaudeAgentOptions(mcp_servers={"memory": memory_server})
    """
    from claude_agent_sdk import tool, create_sdk_mcp_server

    @tool(
        "save_learning",
        "Save a lesson learned from human feedback to persistent memory. "
        "Use this when you learn something new from a human correction or "
        "after 3 failed approval attempts. "
        "The learning will be available in all future agent sessions.\n\n"
        "Parameters:\n"
        "- learning: The lesson learned "
        "(e.g., 'For noissue.co WRO tickets, use orderops@noissue.co')\n"
        "- context: Who taught this and where, "
        "e.g. 'Taught by Nipun on COPS-198277' (optional)",
        {"learning": str, "context": str},
    )
    async def save_learning(args):
        try:
            learning = args["learning"]
            context = args.get("context", "")
            agent.save_memory(learning, context)
            preview = learning[:100] + ("..." if len(learning) > 100 else "")
            return {"content": [{"type": "text", "text": f"Learning saved: {preview}"}]}
        except Exception as e:
            return {
                "content": [{"type": "text", "text": f"Error saving learning: {e}"}],
                "is_error": True,
            }

    return create_sdk_mcp_server(name="memory", tools=[save_learning])
