-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
210 lines (166 loc) Β· 6.86 KB
/
main.py
File metadata and controls
210 lines (166 loc) Β· 6.86 KB
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
import asyncio
import logging
import sys
from typing import Optional
from arxiv_mcp import ArxivMCPClient, ArxivMCPServer
from arxiv_mcp.utils import setup_logging
async def run_server():
"""Run the MCP server."""
setup_logging("INFO")
logger = logging.getLogger(__name__)
try:
server = ArxivMCPServer()
logger.info("Starting arXiv MCP server...")
# Server implementation would go here
# For now, we'll just show that it's ready
logger.info("arXiv MCP server is ready!")
# Keep server running
while True:
await asyncio.sleep(1)
except KeyboardInterrupt:
logger.info("Server stopped by user")
except Exception as e:
logger.error(f"Server error: {e}")
sys.exit(1)
async def test_client():
"""Test the MCP client functionality."""
setup_logging("INFO")
logger = logging.getLogger(__name__)
print("arXiv MCP Client Test Suite")
print("=" * 50)
try:
# Create direct server instance for testing
from arxiv_mcp.server import ArxivMCPServer
server = ArxivMCPServer()
# Test basic search
print("π Testing basic search...")
results = await server.search_arxiv("genai", max_results=3)
if results.get("papers"):
print(f"β
Found {len(results['papers'])} papers")
for i, paper in enumerate(results["papers"][:2], 1):
print(f" {i}. {paper['title'][:60]}...")
print(f" Authors: {', '.join(paper['authors'][:2])}...")
print(f" arXiv ID: {paper['id']}")
else:
print("β No papers found")
return
first_paper_id = results["papers"][0]["id"]
# Test additional tools
print("\nπ§ͺ Testing advanced features...")
# Test author search
print(" π Author search...")
author_results = await server.search_by_author("Geoffrey Hinton", max_results=2)
if author_results.get("papers"):
print(f" β
Found {len(author_results['papers'])} papers by Geoffrey Hinton")
# Test category search
print(" π·οΈ Category search...")
cat_results = await server.search_by_category("cs.AI", max_results=2)
if cat_results.get("papers"):
print(f" β
Found {len(cat_results['papers'])} papers in cs.AI")
# Test recent papers
print(" π
Recent papers...")
recent_results = await server.get_recent_papers("cs.LG", days_back=7, max_results=2)
if recent_results.get("papers"):
print(f" β
Found {len(recent_results['papers'])} recent cs.LG papers")
# Test paper comparison
if len(results["papers"]) >= 2:
print(" βοΈ Paper comparison...")
paper_ids = [p["id"] for p in results["papers"][:2]]
comparison = await server.compare_papers(paper_ids, ["authors", "published"])
if comparison and not comparison.startswith("Error"):
print(" β
Generated paper comparison")
# Test export
print(" πΎ Export functionality...")
export_ids = [results["papers"][0]["id"]]
bibtex_export = await server.export_papers(export_ids, "bibtex", include_abstract=False)
if bibtex_export and not bibtex_export.startswith("Error"):
print(" β
Generated BibTeX export")
# Test related papers
print(" π Related papers...")
related = await server.find_related_papers(first_paper_id, max_results=3)
if related.get("related_papers"):
print(f" β
Found {len(related['related_papers'])} related papers")
# Test trend analysis
print(" π Trend analysis...")
trends = await server.analyze_trends("cs.AI", "1_month", "publication_count")
if trends.get("total_papers", 0) > 0:
print(f" β
Analyzed {trends['total_papers']} papers for trends")
print("\nπ All tests completed successfully!")
except Exception as e:
logger.error(f"Test failed: {e}")
print(f"β Test failed: {e}")
async def demo_usage():
"""Demonstrate typical usage patterns."""
print("arXiv MCP Server - Usage Demo")
print("=" * 40)
from arxiv_mcp.server import ArxivMCPServer
server = ArxivMCPServer()
# Demo 1: Literature search for a research topic
print("\nπ Demo 1: Literature Search")
print("-" * 30)
query = "attention mechanism neural networks"
results = await server.search_arxiv(query, max_results=5)
if results.get("papers"):
print(f"Search: '{query}'")
print(f"Found: {len(results['papers'])} papers\n")
for i, paper in enumerate(results["papers"][:3], 1):
print(f"{i}. {paper['title']}")
print(f" Authors: {', '.join(paper['authors'][:2])}...")
print(f" Categories: {', '.join(paper['categories'][:2])}")
print(f" arXiv ID: {paper['id']}\n")
# Demo 2: Author exploration
print("π¨βπ¬ Demo 2: Author Exploration")
print("-" * 30)
author_results = await server.search_by_author("Yann LeCun", max_results=3)
if author_results.get("papers"):
print(f"Recent papers by Yann LeCun:")
for paper in author_results["papers"][:3]:
print(f"β’ {paper['title']} ({paper['published'][:4]})")
# Demo 3: Export for citation
print("\nπ Demo 3: Citation Export")
print("-" * 30)
if results.get("papers"):
export_ids = [results["papers"][0]["id"]]
bibtex = await server.export_papers(export_ids, "bibtex", include_abstract=False)
print("BibTeX format:")
print(bibtex[:200] + "..." if len(bibtex) > 200 else bibtex)
def print_usage():
"""Print usage information."""
print("""
arXiv MCP Server - Usage:
Commands:
python main.py server Run the MCP server
python main.py test Run client tests
python main.py demo Run usage demonstration
python main.py --help Show this help message
Examples:
python main.py server # Start the server
python main.py test # Test all functionality
python main.py demo # See usage examples
""")
async def main():
"""Main entry point."""
if len(sys.argv) < 2:
await test_client()
return
command = sys.argv[1].lower()
if command == "server":
await run_server()
elif command == "test":
await test_client()
elif command == "demo":
await demo_usage()
elif command in ["--help", "-h", "help"]:
print_usage()
else:
print(f"Unknown command: {command}")
print_usage()
sys.exit(1)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\nπ Goodbye!")
except Exception as e:
print(f"β Error: {e}")
sys.exit(1)