#!/usr/bin/env python3
"""
Generated test file for MCP Tool Error Test
Framework: fastmcp
Execution mode: async
Streaming: no"""

import os
import sentry_sdk
import asyncio

import socket
import threading
from sentry_sdk.integrations.mcp import MCPIntegration
from fastmcp import FastMCP, Client
from fastmcp.client.transports import SSETransport


sentry_sdk.init(
    dsn=os.environ.get("SENTRY_DSN"),
    traces_sample_rate=1.0,
    send_default_pii=True,
    integrations=[MCPIntegration()],
)

mcp_server = FastMCP("test-server")

# Define MCP tools
@mcp_server.tool()
def failing_tool(input: str) -> str:
    """A tool that always fails"""
    raise Exception("Something went wrong in the tool")

def _wait_for_port(port, host="127.0.0.1", timeout=10):
    """Poll until the server is accepting connections on the given port."""
    import time as _time
    deadline = _time.monotonic() + timeout
    while _time.monotonic() < deadline:
        try:
            with socket.create_connection((host, port), timeout=0.5):
                return
        except OSError:
            _time.sleep(0.1)
    raise RuntimeError(f"Server on {host}:{port} did not start within {timeout}s")

SSE_PORT = int(os.environ.get("MCP_SSE_PORT", "8765"))

def run_sse_server():
    """Run the MCP server with SSE transport in a background thread."""
    mcp_server.run(transport="sse", host="127.0.0.1", port=SSE_PORT)

async def main():
    # Start MCP server with SSE transport in background thread
    server_thread = threading.Thread(target=run_sse_server, daemon=True)
    server_thread.start()
    _wait_for_port(SSE_PORT)

    async with Client(SSETransport(f"http://127.0.0.1:{SSE_PORT}/sse")) as client:
        try:
            result = await client.call_tool("failing_tool", {"input":"test"})
            print(f"Tool result: {result}")
        except Exception as e:
            print(f"Tool error (expected): {type(e).__name__}: {e}")
    # Give the server thread time to finish processing and create spans
    await asyncio.sleep(0.5)

if __name__ == "__main__":
    with sentry_sdk.start_transaction(op="test", name="MCP Tool Error Test"):
        asyncio.run(main())
    sentry_sdk.flush(timeout=5)
