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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
"""
arXiv MCP client wrapper for accessing arXiv papers via Model Context Protocol.
Uses in-process handler calls instead of subprocess stdio protocol.
"""
import os
import logging
import sys
from typing import List, Optional, Any, Dict
from pathlib import Path
from datetime import datetime
from tenacity import retry, stop_after_attempt, wait_exponential
import json
import asyncio
import nest_asyncio
import urllib.request
import urllib.error

from utils.schemas import Paper

# MCP handlers will be imported lazily in __init__ after configuring sys.argv
# This ensures the Settings class reads the correct storage path

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


class MCPArxivClient:
    """Wrapper for arXiv MCP server using direct in-process handler calls."""

    # Class-level handlers (imported once)
    _handlers_imported = False
    handle_search = None
    handle_download = None
    handle_list_papers = None

    @classmethod
    def _import_handlers(cls):
        """Import MCP handlers once at class level."""
        if not cls._handlers_imported:
            from arxiv_mcp_server.tools import handle_search, handle_download, handle_list_papers
            cls.handle_search = handle_search
            cls.handle_download = handle_download
            cls.handle_list_papers = handle_list_papers
            cls._handlers_imported = True

    def __init__(self, storage_path: Optional[str] = None):
        """
        Initialize MCP arXiv client with in-process handlers.

        Args:
            storage_path: Path where papers are stored (reads from env if not provided)
        """
        self.storage_path = Path(storage_path or os.getenv("MCP_ARXIV_STORAGE_PATH", "data/mcp_papers"))
        self.storage_path.mkdir(parents=True, exist_ok=True)

        # Set sys.argv BEFORE importing handlers (first time only)
        self._original_argv = sys.argv.copy()
        if not self._handlers_imported:
            # Only set on first initialization
            if "--storage-path" not in sys.argv:
                sys.argv.extend(["--storage-path", str(self.storage_path.resolve())])
                logger.debug(f"Set sys.argv storage path: {self.storage_path.resolve()}")

        # Import handlers (only happens once)
        self._import_handlers()

        # Import settings AFTER handlers to get configured instance
        from arxiv_mcp_server.config import Settings as MCPSettings
        import arxiv_mcp_server.tools.download as download_module

        # Update the module-level settings in download.py to use our storage path
        # This is a workaround since Settings is instantiated at module load time
        if hasattr(download_module, 'settings'):
            # Monkey-patch the storage path for this instance
            logger.debug(f"Updating download module settings storage path")

        logger.info(f"MCPArxivClient initialized with in-process handlers")
        logger.info(f"Storage path: {self.storage_path.resolve()}")

        # Log existing files in storage
        existing_files = list(self.storage_path.glob("*.pdf"))
        logger.info(f"Storage directory contains {len(existing_files)} existing PDF files")

    async def _call_handler_async(self, handler_func, arguments: Dict[str, Any], handler_name: str) -> Any:
        """
        Call an MCP handler function directly and return parsed result.

        Args:
            handler_func: The async handler function to call
            arguments: Handler arguments as dictionary
            handler_name: Name of handler (for logging)

        Returns:
            Parsed handler result (dict or list)

        Raises:
            Exception: If handler call fails
        """
        try:
            logger.debug(f"Calling {handler_name} with arguments: {arguments}")

            # Call the handler directly (returns List[types.TextContent])
            result = await handler_func(arguments)

            # Extract text from TextContent objects
            if result and len(result) > 0:
                text_content = result[0].text
                logger.debug(f"Raw {handler_name} response: {text_content[:200]}...")

                # Parse JSON response
                try:
                    parsed_data = json.loads(text_content)
                    logger.debug(f"Parsed {handler_name} response type: {type(parsed_data)}")

                    # Check for errors in response
                    if isinstance(parsed_data, dict) and "error" in parsed_data:
                        logger.error(f"{handler_name} returned error: {parsed_data['error']}")

                    return parsed_data
                except json.JSONDecodeError:
                    logger.warning(f"Could not parse {handler_name} response as JSON: {text_content[:200]}")
                    return text_content
            else:
                logger.warning(f"{handler_name} returned empty result")
                return {}

        except Exception as e:
            logger.error(f"Error calling {handler_name}: {str(e)}")
            raise

    def _download_from_arxiv_direct(self, paper: Paper) -> Optional[Path]:
        """
        Fallback method to download PDF directly from arXiv.
        Used when MCP server download fails or file is not accessible.

        Args:
            paper: Paper object

        Returns:
            Path to downloaded PDF, or None if download fails
        """
        try:
            pdf_path = self.storage_path / f"{paper.arxiv_id}.pdf"

            logger.info(f"Attempting direct download from arXiv for {paper.arxiv_id}")
            logger.debug(f"PDF URL: {paper.pdf_url}")

            # Download with urllib
            headers = {'User-Agent': 'Mozilla/5.0 (Research Paper Analysis System)'}
            request = urllib.request.Request(paper.pdf_url, headers=headers)

            with urllib.request.urlopen(request, timeout=30) as response:
                pdf_content = response.read()

            # Write to storage
            pdf_path.write_bytes(pdf_content)
            logger.info(f"Successfully downloaded {len(pdf_content)} bytes to {pdf_path}")

            return pdf_path

        except urllib.error.HTTPError as e:
            logger.error(f"HTTP error downloading from arXiv: {e.code} {e.reason}")
            return None
        except urllib.error.URLError as e:
            logger.error(f"URL error downloading from arXiv: {str(e)}")
            return None
        except Exception as e:
            logger.error(f"Unexpected error in direct arXiv download: {str(e)}", exc_info=True)
            return None


    def _parse_mcp_paper(self, paper_data: Dict[str, Any]) -> Paper:
        """
        Convert MCP tool response to Paper object with robust type validation.

        Args:
            paper_data: Paper data from MCP tool

        Returns:
            Paper object with validated and normalized fields

        Raises:
            Exception: If critical fields are missing or invalid
        """
        try:
            # MCP server returns papers with these fields
            # Handle potential variations in response format
            arxiv_id = paper_data.get("id") or paper_data.get("arxiv_id", "")
            if not arxiv_id:
                raise ValueError("Missing required field: arxiv_id")

            # Parse published date with robust error handling
            published_str = paper_data.get("published", "")
            if isinstance(published_str, str):
                try:
                    published = datetime.fromisoformat(published_str.replace('Z', '+00:00'))
                except Exception as e:
                    logger.warning(f"Failed to parse published date '{published_str}': {e}, using current time")
                    published = datetime.now()
            elif isinstance(published_str, datetime):
                published = published_str
            else:
                logger.warning(f"Published field has unexpected type: {type(published_str)}, using current time")
                published = datetime.now()

            # Normalize authors field - handle various formats
            authors_raw = paper_data.get("authors", [])
            if isinstance(authors_raw, list):
                # Ensure all elements are strings
                authors = [str(author) if not isinstance(author, str) else author for author in authors_raw]
            elif isinstance(authors_raw, dict):
                # Dict format - log warning and extract
                logger.warning(f"Authors field is dict for paper {arxiv_id}: {authors_raw}")
                if 'names' in authors_raw:
                    authors = authors_raw['names'] if isinstance(authors_raw['names'], list) else [str(authors_raw['names'])]
                else:
                    authors = [str(val) for val in authors_raw.values() if val]
            elif isinstance(authors_raw, str):
                authors = [authors_raw]
            else:
                logger.warning(f"Unexpected authors format for paper {arxiv_id}: {type(authors_raw)}")
                authors = []

            # Normalize categories field - handle various formats
            categories_raw = paper_data.get("categories", [])
            if isinstance(categories_raw, list):
                # Ensure all elements are strings
                categories = [str(cat) if not isinstance(cat, str) else cat for cat in categories_raw]
            elif isinstance(categories_raw, dict):
                # Dict format - log warning and extract
                logger.warning(f"Categories field is dict for paper {arxiv_id}: {categories_raw}")
                if 'categories' in categories_raw:
                    categories = categories_raw['categories'] if isinstance(categories_raw['categories'], list) else [str(categories_raw['categories'])]
                else:
                    categories = [str(val) for val in categories_raw.values() if val]
            elif isinstance(categories_raw, str):
                categories = [categories_raw]
            else:
                logger.warning(f"Unexpected categories format for paper {arxiv_id}: {type(categories_raw)}")
                categories = []

            # Normalize title field
            title_raw = paper_data.get("title", "")
            if isinstance(title_raw, dict):
                logger.warning(f"Title field is dict for paper {arxiv_id}: {title_raw}")
                title = title_raw.get("title") or str(title_raw)
            else:
                title = str(title_raw) if title_raw else ""

            # Normalize abstract field
            abstract_raw = paper_data.get("summary") or paper_data.get("abstract", "")
            if isinstance(abstract_raw, dict):
                logger.warning(f"Abstract field is dict for paper {arxiv_id}: {abstract_raw}")
                abstract = abstract_raw.get("abstract") or abstract_raw.get("summary") or str(abstract_raw)
            else:
                abstract = str(abstract_raw) if abstract_raw else ""

            # Normalize PDF URL field
            pdf_url_raw = paper_data.get("pdf_url")
            if pdf_url_raw:
                if isinstance(pdf_url_raw, dict):
                    logger.warning(f"pdf_url field is dict for paper {arxiv_id}: {pdf_url_raw}")
                    pdf_url = pdf_url_raw.get("url") or pdf_url_raw.get("pdf_url") or f"https://arxiv.org/pdf/{arxiv_id}.pdf"
                else:
                    pdf_url = str(pdf_url_raw)
            else:
                pdf_url = f"https://arxiv.org/pdf/{arxiv_id}.pdf"

            # Create Paper object with normalized data
            # Pydantic validators will provide additional validation
            paper = Paper(
                arxiv_id=arxiv_id,
                title=title,
                authors=authors,
                abstract=abstract,
                pdf_url=pdf_url,
                published=published,
                categories=categories
            )

            logger.debug(f"Successfully parsed paper {arxiv_id}: {len(authors)} authors, {len(categories)} categories")
            return paper

        except Exception as e:
            logger.error(f"Error parsing MCP paper data: {str(e)}")
            logger.error(f"Raw paper data: {paper_data}")
            raise

    @retry(
        stop=stop_after_attempt(3),
        wait=wait_exponential(multiplier=1, min=4, max=10)
    )
    async def search_papers_async(
        self,
        query: str,
        max_results: int = 5,
        category: Optional[str] = None,
        sort_by: str = "relevance"
    ) -> List[Paper]:
        """
        Search for papers on arXiv using direct MCP handler calls.

        Args:
            query: Search query
            max_results: Maximum number of papers to return
            category: Optional arXiv category filter (e.g., 'cs.AI')
            sort_by: Sort criterion (relevance, lastUpdatedDate, submittedDate)

        Returns:
            List of Paper objects

        Raises:
            Exception: If handler call fails after retries
        """
        try:
            logger.info(f"Searching arXiv via MCP for: {query}")

            # Prepare handler arguments
            search_args = {
                "query": query,
                "max_results": max_results,
                "sort_by": sort_by
            }

            # MCP uses "categories" (plural) instead of "category"
            if category:
                search_args["categories"] = [category]

            # Call handle_search directly (it's a module-level async function, not a method)
            result = await self._call_handler_async(MCPArxivClient.handle_search, search_args, "handle_search")

            # Parse results
            papers = []
            if isinstance(result, dict):
                paper_list = result.get("papers", [])
            elif isinstance(result, list):
                paper_list = result
            else:
                logger.warning(f"Unexpected result format: {type(result)}")
                paper_list = []

            for paper_data in paper_list:
                try:
                    paper = self._parse_mcp_paper(paper_data)
                    papers.append(paper)
                except Exception as e:
                    logger.warning(f"Failed to parse paper: {str(e)}")
                    continue

            logger.info(f"Found {len(papers)} papers via MCP")
            return papers

        except Exception as e:
            logger.error(f"Error searching arXiv via MCP: {str(e)}")
            raise

    def search_papers(
        self,
        query: str,
        max_results: int = 5,
        category: Optional[str] = None,
        sort_by: str = "relevance"
    ) -> List[Paper]:
        """
        Synchronous wrapper for search_papers_async.

        Args:
            query: Search query
            max_results: Maximum number of papers to return
            category: Optional arXiv category filter
            sort_by: Sort criterion

        Returns:
            List of Paper objects
        """
        import asyncio
        import nest_asyncio

        # Get or create event loop
        try:
            loop = asyncio.get_event_loop()
            # Check if loop is closed
            if loop.is_closed():
                # Create new loop if closed
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
        except RuntimeError:
            # Create new event loop if none exists
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

        # Enable nested event loops for compatibility
        nest_asyncio.apply(loop)

        return loop.run_until_complete(
            self.search_papers_async(query, max_results, category, sort_by)
        )

    @retry(
        stop=stop_after_attempt(3),
        wait=wait_exponential(multiplier=1, min=4, max=10)
    )
    async def download_paper_async(self, paper: Paper) -> Optional[Path]:
        """
        Download paper PDF using direct MCP handler calls.

        The MCP server downloads PDFs and converts to Markdown, but we only need the PDF.
        With in-process handlers, we can access the PDF directly from storage.

        Args:
            paper: Paper object

        Returns:
            Path to downloaded PDF, or None if download fails
        """
        try:
            # Expected path in storage (MCP handler downloads to STORAGE_PATH)
            pdf_path = self.storage_path / f"{paper.arxiv_id}.pdf"

            # Check if already exists
            if pdf_path.exists():
                logger.info(f"Paper {paper.arxiv_id} already in storage")
                return pdf_path

            logger.info(f"Downloading paper {paper.arxiv_id} via MCP handler")
            logger.debug(f"Expected download path: {pdf_path}")

            # Call handle_download directly (it's a module-level async function, not a method)
            result = await self._call_handler_async(
                MCPArxivClient.handle_download,
                {"paper_id": paper.arxiv_id},
                "handle_download"
            )

            # Log the response for debugging
            logger.debug(f"MCP download response: {result}")

            # Check for error in response
            if isinstance(result, dict):
                if result.get("status") == "error":
                    error_msg = result.get("message", "Unknown error")
                    logger.error(f"MCP download failed for {paper.arxiv_id}: {error_msg}")
                    # Fall back to direct download
                    return self._download_from_arxiv_direct(paper)

            # With in-process handlers, the file should be directly accessible
            # The handler downloads to STORAGE_PATH configured via settings
            if pdf_path.exists():
                logger.info(f"Successfully downloaded paper to {pdf_path}")
                return pdf_path

            # If not at expected path, search storage directory
            storage_files = list(self.storage_path.glob("*.pdf"))
            matching_files = [f for f in storage_files if paper.arxiv_id in f.name]
            if matching_files:
                found_file = matching_files[0]
                logger.info(f"Found downloaded file: {found_file}")
                return found_file

            # File not found - fall back to direct download
            logger.warning(f"MCP download completed but PDF not found for {paper.arxiv_id}")
            logger.warning("Falling back to direct arXiv download...")
            return self._download_from_arxiv_direct(paper)

        except Exception as e:
            logger.error(f"Error downloading paper {paper.arxiv_id} via MCP: {str(e)}", exc_info=True)
            logger.warning("Attempting direct arXiv download as fallback...")
            return self._download_from_arxiv_direct(paper)

    def download_paper(self, paper: Paper) -> Optional[Path]:
        """
        Synchronous wrapper for download_paper_async.

        Args:
            paper: Paper object

        Returns:
            Path to downloaded PDF
        """
        import asyncio
        import nest_asyncio

        # Get or create event loop
        try:
            loop = asyncio.get_event_loop()
            # Check if loop is closed
            if loop.is_closed():
                # Create new loop if closed
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
        except RuntimeError:
            # Create new event loop if none exists
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

        # Enable nested event loops for compatibility
        nest_asyncio.apply(loop)

        return loop.run_until_complete(self.download_paper_async(paper))

    def download_papers(self, papers: List[Paper]) -> List[Path]:
        """
        Download multiple papers.

        Args:
            papers: List of Paper objects

        Returns:
            List of Paths to downloaded PDFs
        """
        paths = []
        for paper in papers:
            path = self.download_paper(paper)
            if path:
                paths.append(path)
        return paths

    async def get_cached_papers_async(self) -> List[Path]:
        """
        Get list of cached paper PDFs using direct MCP handler calls.

        Returns:
            List of Paths to cached PDFs
        """
        try:
            # Call handle_list_papers directly (it's a module-level async function, not a method)
            result = await self._call_handler_async(MCPArxivClient.handle_list_papers, {}, "handle_list_papers")

            # Parse result to get paths
            if isinstance(result, dict):
                paper_ids = result.get("papers", [])
            elif isinstance(result, list):
                paper_ids = result
            else:
                logger.warning("Unexpected format from list_papers")
                paper_ids = []

            # Convert to paths
            paths = [self.storage_path / f"{pid}.pdf" for pid in paper_ids
                    if (self.storage_path / f"{pid}.pdf").exists()]

            return paths
        except Exception as e:
            logger.warning(f"Error listing cached papers via MCP: {str(e)}")
            # Fallback to filesystem listing
            return list(self.storage_path.glob("*.pdf"))

    def get_cached_papers(self) -> List[Path]:
        """
        Synchronous wrapper for get_cached_papers_async.

        Returns:
            List of Paths to cached PDFs
        """
        import asyncio
        import nest_asyncio

        # Get or create event loop
        try:
            loop = asyncio.get_event_loop()
            # Check if loop is closed
            if loop.is_closed():
                # Create new loop if closed
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
        except RuntimeError:
            # Create new event loop if none exists
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

        # Enable nested event loops for compatibility
        nest_asyncio.apply(loop)

        return loop.run_until_complete(self.get_cached_papers_async())

    def __del__(self):
        """Cleanup on deletion - restore original sys.argv."""
        try:
            # Restore original sys.argv to avoid side effects
            sys.argv = self._original_argv
        except Exception:
            pass  # Ignore errors during cleanup