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

import os
import sentry_sdk
import asyncio

import json
import anyio
from sentry_sdk.integrations.mcp import MCPIntegration
from mcp.client.session import ClientSession
from mcp.server.fastmcp import FastMCP


sentry_sdk.init(
    dsn=os.environ.get("SENTRY_DSN"),
    traces_sample_rate=1.0,
    send_default_pii=True,
    stream_gen_ai_spans=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")


async def main():
    # Use in-memory streams for in-process client-server communication
    server = mcp_server._mcp_server
    c2s_send, c2s_recv = anyio.create_memory_object_stream(0)
    s2c_send, s2c_recv = anyio.create_memory_object_stream(0)

    async with anyio.create_task_group() as tg:
        tg.start_soon(
            server.run,
            c2s_recv,
            s2c_send,
            server.create_initialization_options(),
        )
        async with ClientSession(s2c_recv, c2s_send) as session:
            await session.initialize()
            try:
                result = await session.call_tool("failing_tool", {"input":"test"})
                print(f"Tool result: {result}")
            except Exception as e:
                print(f"Tool error (expected): {type(e).__name__}: {e}")
        tg.cancel_scope.cancel()

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