|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +ArXiv LaTeX MCP Server |
| 4 | +
|
| 5 | +This server provides tools to fetch and process arXiv papers' LaTeX source code |
| 6 | +for better mathematical expression interpretation. |
| 7 | +""" |
| 8 | + |
| 9 | +import contextlib |
| 10 | +import logging |
| 11 | +import os |
| 12 | +from collections.abc import AsyncIterator |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +import click |
| 16 | +import mcp.types as types |
| 17 | +import uvicorn |
| 18 | +from mcp.server.lowlevel import Server |
| 19 | +from mcp.server.sse import SseServerTransport |
| 20 | +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager |
| 21 | +from starlette.applications import Starlette |
| 22 | +from starlette.responses import Response |
| 23 | +from starlette.routing import Mount, Route |
| 24 | +from starlette.types import Receive, Scope, Send |
| 25 | + |
| 26 | +from arxiv_to_prompt import process_latex_source, list_sections, extract_section |
| 27 | + |
| 28 | +# Configure logging |
| 29 | +logger = logging.getLogger(__name__) |
| 30 | + |
| 31 | +ARXIV_MCP_SERVER_PORT = int(os.getenv("ARXIV_MCP_SERVER_PORT", "5000")) |
| 32 | + |
| 33 | + |
| 34 | +@click.command() |
| 35 | +@click.option( |
| 36 | + "--port", default=ARXIV_MCP_SERVER_PORT, help="Port to listen on for HTTP" |
| 37 | +) |
| 38 | +@click.option( |
| 39 | + "--log-level", |
| 40 | + default="INFO", |
| 41 | + help="Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)", |
| 42 | +) |
| 43 | +@click.option( |
| 44 | + "--json-response", |
| 45 | + is_flag=True, |
| 46 | + default=False, |
| 47 | + help="Enable JSON responses for StreamableHTTP instead of SSE streams", |
| 48 | +) |
| 49 | +def main( |
| 50 | + port: int, |
| 51 | + log_level: str, |
| 52 | + json_response: bool, |
| 53 | +) -> int: |
| 54 | + # Configure logging |
| 55 | + logging.basicConfig( |
| 56 | + level=getattr(logging, log_level.upper()), |
| 57 | + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", |
| 58 | + ) |
| 59 | + |
| 60 | + # Configure webshare proxy for arxiv_to_prompt (uses requests library). |
| 61 | + # Set PROXY_USERNAME and PROXY_PASSWORD env vars to enable. |
| 62 | + proxy_user = os.environ.get("PROXY_USERNAME") |
| 63 | + proxy_pass = os.environ.get("PROXY_PASSWORD") |
| 64 | + if proxy_user and proxy_pass: |
| 65 | + proxy_host = os.environ.get("PROXY_HOST", "p.webshare.io") |
| 66 | + proxy_port = os.environ.get("PROXY_PORT", "80") |
| 67 | + proxy_url = f"http://{proxy_user}:{proxy_pass}@{proxy_host}:{proxy_port}" |
| 68 | + os.environ.setdefault("HTTP_PROXY", proxy_url) |
| 69 | + os.environ.setdefault("HTTPS_PROXY", proxy_url) |
| 70 | + logger.info(f"Proxy configured: http://{proxy_host}:{proxy_port}") |
| 71 | + |
| 72 | + # Create the MCP server instance |
| 73 | + app = Server("arxiv-latex-mcp") |
| 74 | + |
| 75 | + @app.list_tools() |
| 76 | + async def handle_list_tools() -> list[types.Tool]: |
| 77 | + """List available tools.""" |
| 78 | + return [ |
| 79 | + types.Tool( |
| 80 | + name="get_paper_prompt", |
| 81 | + description="Get a flattened LaTeX code of a paper from arXiv ID for precise interpretation of mathematical expressions", |
| 82 | + inputSchema={ |
| 83 | + "type": "object", |
| 84 | + "properties": { |
| 85 | + "arxiv_id": { |
| 86 | + "type": "string", |
| 87 | + "description": "The arXiv ID of the paper (e.g., '2403.12345')", |
| 88 | + } |
| 89 | + }, |
| 90 | + "required": ["arxiv_id"], |
| 91 | + }, |
| 92 | + ), |
| 93 | + types.Tool( |
| 94 | + name="get_paper_abstract", |
| 95 | + description="Get just the abstract of an arXiv paper (faster and cheaper than fetching the full paper)", |
| 96 | + inputSchema={ |
| 97 | + "type": "object", |
| 98 | + "properties": { |
| 99 | + "arxiv_id": { |
| 100 | + "type": "string", |
| 101 | + "description": "The arXiv ID of the paper (e.g., '2403.12345')", |
| 102 | + } |
| 103 | + }, |
| 104 | + "required": ["arxiv_id"], |
| 105 | + }, |
| 106 | + ), |
| 107 | + types.Tool( |
| 108 | + name="list_paper_sections", |
| 109 | + description="List section headings of an arXiv paper to see its structure", |
| 110 | + inputSchema={ |
| 111 | + "type": "object", |
| 112 | + "properties": { |
| 113 | + "arxiv_id": { |
| 114 | + "type": "string", |
| 115 | + "description": "The arXiv ID of the paper (e.g., '2403.12345')", |
| 116 | + } |
| 117 | + }, |
| 118 | + "required": ["arxiv_id"], |
| 119 | + }, |
| 120 | + ), |
| 121 | + types.Tool( |
| 122 | + name="get_paper_section", |
| 123 | + description="Get a specific section of an arXiv paper by section path (use list_paper_sections first to find available sections)", |
| 124 | + inputSchema={ |
| 125 | + "type": "object", |
| 126 | + "properties": { |
| 127 | + "arxiv_id": { |
| 128 | + "type": "string", |
| 129 | + "description": "The arXiv ID of the paper (e.g., '2403.12345')", |
| 130 | + }, |
| 131 | + "section_path": { |
| 132 | + "type": "string", |
| 133 | + "description": "The section path to extract (e.g., '1', '2.1', 'Introduction'). Use list_paper_sections to find available paths.", |
| 134 | + }, |
| 135 | + }, |
| 136 | + "required": ["arxiv_id", "section_path"], |
| 137 | + }, |
| 138 | + ), |
| 139 | + ] |
| 140 | + |
| 141 | + LATEX_RENDER_INSTRUCTIONS = """ |
| 142 | +
|
| 143 | +IMPORTANT INSTRUCTIONS FOR RENDERING: |
| 144 | +When discussing this paper, please use dollar sign notation ($...$) for inline equations and double dollar signs ($$...$$) for display equations when providing responses that include LaTeX mathematical expressions. |
| 145 | +""" |
| 146 | + |
| 147 | + @app.call_tool() |
| 148 | + async def handle_call_tool( |
| 149 | + name: str, arguments: dict[str, Any] | None |
| 150 | + ) -> list[types.TextContent]: |
| 151 | + """Handle tool calls.""" |
| 152 | + if not arguments or "arxiv_id" not in arguments: |
| 153 | + raise ValueError("Missing required argument: arxiv_id") |
| 154 | + |
| 155 | + arxiv_id = arguments["arxiv_id"] |
| 156 | + |
| 157 | + try: |
| 158 | + if name == "get_paper_prompt": |
| 159 | + logger.info(f"Processing arXiv paper: {arxiv_id}") |
| 160 | + prompt = process_latex_source(arxiv_id) |
| 161 | + result = prompt + LATEX_RENDER_INSTRUCTIONS |
| 162 | + logger.info(f"Successfully processed arXiv paper: {arxiv_id}") |
| 163 | + |
| 164 | + elif name == "get_paper_abstract": |
| 165 | + logger.info(f"Getting abstract for arXiv paper: {arxiv_id}") |
| 166 | + result = process_latex_source(arxiv_id, abstract_only=True) |
| 167 | + logger.info(f"Successfully got abstract for: {arxiv_id}") |
| 168 | + |
| 169 | + elif name == "list_paper_sections": |
| 170 | + logger.info(f"Listing sections for arXiv paper: {arxiv_id}") |
| 171 | + text = process_latex_source(arxiv_id) |
| 172 | + sections = list_sections(text) |
| 173 | + result = "\n".join(sections) |
| 174 | + logger.info(f"Successfully listed sections for: {arxiv_id}") |
| 175 | + |
| 176 | + elif name == "get_paper_section": |
| 177 | + if "section_path" not in arguments: |
| 178 | + raise ValueError("Missing required argument: section_path") |
| 179 | + section_path = arguments["section_path"] |
| 180 | + logger.info(f"Getting section '{section_path}' for arXiv paper: {arxiv_id}") |
| 181 | + text = process_latex_source(arxiv_id) |
| 182 | + result = extract_section(text, section_path) |
| 183 | + if result is None: |
| 184 | + result = f"Section '{section_path}' not found. Use list_paper_sections to see available sections." |
| 185 | + else: |
| 186 | + result = result + LATEX_RENDER_INSTRUCTIONS |
| 187 | + logger.info(f"Successfully got section for: {arxiv_id}") |
| 188 | + |
| 189 | + else: |
| 190 | + raise ValueError(f"Unknown tool: {name}") |
| 191 | + |
| 192 | + return [types.TextContent(type="text", text=result)] |
| 193 | + |
| 194 | + except Exception as e: |
| 195 | + error_msg = f"Error processing arXiv paper {arxiv_id}: {str(e)}" |
| 196 | + logger.error(error_msg) |
| 197 | + |
| 198 | + return [types.TextContent(type="text", text=error_msg)] |
| 199 | + |
| 200 | + # Set up SSE transport |
| 201 | + sse = SseServerTransport("/messages/") |
| 202 | + |
| 203 | + async def handle_sse(request): |
| 204 | + logger.info("Handling SSE connection") |
| 205 | + async with sse.connect_sse( |
| 206 | + request.scope, request.receive, request._send |
| 207 | + ) as streams: |
| 208 | + await app.run( |
| 209 | + streams[0], streams[1], app.create_initialization_options() |
| 210 | + ) |
| 211 | + return Response() |
| 212 | + |
| 213 | + # Set up StreamableHTTP transport |
| 214 | + session_manager = StreamableHTTPSessionManager( |
| 215 | + app=app, |
| 216 | + event_store=None, |
| 217 | + json_response=json_response, |
| 218 | + stateless=True, |
| 219 | + ) |
| 220 | + |
| 221 | + async def handle_streamable_http( |
| 222 | + scope: Scope, receive: Receive, send: Send |
| 223 | + ) -> None: |
| 224 | + logger.info("Handling StreamableHTTP request") |
| 225 | + await session_manager.handle_request(scope, receive, send) |
| 226 | + |
| 227 | + @contextlib.asynccontextmanager |
| 228 | + async def lifespan(app: Starlette) -> AsyncIterator[None]: |
| 229 | + """Context manager for session manager.""" |
| 230 | + async with session_manager.run(): |
| 231 | + logger.info("Application started with dual transports!") |
| 232 | + try: |
| 233 | + yield |
| 234 | + finally: |
| 235 | + logger.info("Application shutting down...") |
| 236 | + |
| 237 | + # Create an ASGI application with routes for both transports |
| 238 | + starlette_app = Starlette( |
| 239 | + debug=True, |
| 240 | + routes=[ |
| 241 | + # SSE routes |
| 242 | + Route("/sse", endpoint=handle_sse, methods=["GET"]), |
| 243 | + Mount("/messages/", app=sse.handle_post_message), |
| 244 | + # StreamableHTTP route |
| 245 | + Mount("/mcp", app=handle_streamable_http), |
| 246 | + ], |
| 247 | + lifespan=lifespan, |
| 248 | + ) |
| 249 | + |
| 250 | + logger.info(f"Server starting on port {port} with dual transports:") |
| 251 | + logger.info(f" - SSE endpoint: http://localhost:{port}/sse") |
| 252 | + logger.info(f" - StreamableHTTP endpoint: http://localhost:{port}/mcp") |
| 253 | + |
| 254 | + uvicorn.run(starlette_app, host="0.0.0.0", port=port) |
| 255 | + |
| 256 | + return 0 |
| 257 | + |
| 258 | + |
| 259 | +if __name__ == "__main__": |
| 260 | + main() |
0 commit comments