academia-mcp 1.2.2__py3-none-any.whl → 1.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
academia_mcp/files.py CHANGED
@@ -5,6 +5,7 @@ from pathlib import Path
5
5
  DIR_PATH = Path(__file__).parent
6
6
  ROOT_PATH = DIR_PATH.parent
7
7
  DEFAULT_WORKSPACE_DIR_PATH: Path = DIR_PATH / "workdir"
8
+ DEFAULT_LATEX_TEMPLATES_DIR_PATH: Path = DIR_PATH / "latex_templates"
8
9
 
9
10
 
10
11
  class WorkspaceDirectory:
academia_mcp/server.py CHANGED
@@ -12,7 +12,12 @@ from .tools.s2_citations import s2_get_citations, s2_get_references
12
12
  from .tools.hf_datasets_search import hf_datasets_search
13
13
  from .tools.anthology_search import anthology_search
14
14
  from .tools.document_qa import document_qa
15
- from .tools.md_to_pdf import md_to_pdf
15
+ from .tools.latex import (
16
+ compile_latex_from_file,
17
+ compile_latex_from_str,
18
+ get_latex_template,
19
+ get_latex_templates_list,
20
+ )
16
21
  from .tools.web_search import web_search, tavily_web_search, exa_web_search, brave_web_search
17
22
  from .tools.visit_webpage import visit_webpage
18
23
  from .tools.bitflip import (
@@ -33,7 +38,7 @@ def find_free_port() -> int:
33
38
  return port
34
39
  except Exception:
35
40
  continue
36
- return 5000
41
+ raise RuntimeError("No free port in range 5000-6000 found")
37
42
 
38
43
 
39
44
  def run(
@@ -42,6 +47,8 @@ def run(
42
47
  mount_path: str = "/",
43
48
  streamable_http_path: str = "/mcp",
44
49
  transport: Literal["stdio", "sse", "streamable-http"] = "streamable-http",
50
+ disable_web_search_tools: bool = False,
51
+ disable_llm_tools: bool = False,
45
52
  ) -> None:
46
53
  server = FastMCP(
47
54
  "Academia MCP",
@@ -56,21 +63,26 @@ def run(
56
63
  server.add_tool(s2_get_references)
57
64
  server.add_tool(hf_datasets_search)
58
65
  server.add_tool(anthology_search)
59
- server.add_tool(md_to_pdf)
66
+ server.add_tool(compile_latex_from_file)
67
+ server.add_tool(compile_latex_from_str)
68
+ server.add_tool(get_latex_template)
69
+ server.add_tool(get_latex_templates_list)
60
70
  server.add_tool(visit_webpage)
61
- server.add_tool(extract_bitflip_info)
62
- server.add_tool(generate_research_proposal)
63
- server.add_tool(score_research_proposals)
64
71
 
65
- if os.getenv("TAVILY_API_KEY"):
66
- server.add_tool(tavily_web_search)
67
- if os.getenv("EXA_API_KEY"):
68
- server.add_tool(exa_web_search)
69
- if os.getenv("BRAVE_API_KEY"):
70
- server.add_tool(brave_web_search)
71
- if os.getenv("EXA_API_KEY") or os.getenv("BRAVE_API_KEY") or os.getenv("TAVILY_API_KEY"):
72
- server.add_tool(web_search)
73
- if os.getenv("OPENROUTER_API_KEY"):
72
+ if not disable_web_search_tools:
73
+ if os.getenv("TAVILY_API_KEY"):
74
+ server.add_tool(tavily_web_search)
75
+ if os.getenv("EXA_API_KEY"):
76
+ server.add_tool(exa_web_search)
77
+ if os.getenv("BRAVE_API_KEY"):
78
+ server.add_tool(brave_web_search)
79
+ if os.getenv("EXA_API_KEY") or os.getenv("BRAVE_API_KEY") or os.getenv("TAVILY_API_KEY"):
80
+ server.add_tool(web_search)
81
+
82
+ if not disable_llm_tools and os.getenv("OPENROUTER_API_KEY"):
83
+ server.add_tool(extract_bitflip_info)
84
+ server.add_tool(generate_research_proposal)
85
+ server.add_tool(score_research_proposals)
74
86
  server.add_tool(document_qa)
75
87
 
76
88
  if port is None:
@@ -4,7 +4,12 @@ from .arxiv_download import arxiv_download
4
4
  from .hf_datasets_search import hf_datasets_search
5
5
  from .s2_citations import s2_get_references, s2_get_citations
6
6
  from .document_qa import document_qa
7
- from .md_to_pdf import md_to_pdf
7
+ from .latex import (
8
+ compile_latex_from_file,
9
+ compile_latex_from_str,
10
+ get_latex_template,
11
+ get_latex_templates_list,
12
+ )
8
13
  from .web_search import web_search, tavily_web_search, exa_web_search, brave_web_search
9
14
  from .visit_webpage import visit_webpage
10
15
  from .bitflip import extract_bitflip_info, generate_research_proposal, score_research_proposals
@@ -18,7 +23,10 @@ __all__ = [
18
23
  "s2_get_citations",
19
24
  "hf_datasets_search",
20
25
  "document_qa",
21
- "md_to_pdf",
26
+ "compile_latex_from_file",
27
+ "compile_latex_from_str",
28
+ "get_latex_template",
29
+ "get_latex_templates_list",
22
30
  "web_search",
23
31
  "tavily_web_search",
24
32
  "exa_web_search",
@@ -34,20 +34,13 @@ def _format_authors(authors: List[Any]) -> str:
34
34
  return result
35
35
 
36
36
 
37
- def _format_date(date_str: str) -> str:
38
- try:
39
- return datetime.strptime(date_str, "%Y").strftime("%B %d, %Y")
40
- except ValueError:
41
- return date_str
42
-
43
-
44
37
  def _clean_entry(entry: Any) -> Dict[str, Any]:
45
38
  return {
46
39
  "id": entry.full_id,
47
40
  "title": _format_text_field(entry.title.as_text()),
48
41
  "authors": _format_authors(entry.authors),
49
42
  "abstract": (_format_text_field(entry.abstract.as_text()) if entry.abstract else ""),
50
- "published": _format_date(entry.year),
43
+ "published_year": entry.year,
51
44
  "categories": ", ".join(entry.venue_ids),
52
45
  "comment": entry.note if entry.note else "",
53
46
  "url": entry.pdf.url if entry.pdf else "",
@@ -35,6 +35,8 @@ def parse_pdf_file(pdf_path: Path) -> List[str]:
35
35
  for page_number, page in enumerate(reader.pages, start=1):
36
36
  try:
37
37
  text = page.extract_text()
38
+ if not text:
39
+ continue
38
40
  prefix = f"## Page {page_number}\n\n"
39
41
  pages.append(prefix + text)
40
42
  except Exception:
@@ -6,6 +6,7 @@ from dotenv import load_dotenv
6
6
  from pydantic import BaseModel
7
7
 
8
8
  from academia_mcp.llm import llm_acall
9
+ from academia_mcp.utils import truncate_content
9
10
 
10
11
  load_dotenv()
11
12
 
@@ -62,9 +63,11 @@ async def document_qa(
62
63
  assert question and question.strip(), "Please provide non-empty 'question'"
63
64
  if isinstance(document, dict):
64
65
  document = json.dumps(document)
65
-
66
66
  assert document and document.strip(), "Please provide non-empty 'document'"
67
67
 
68
+ question = truncate_content(question, 10000)
69
+ document = truncate_content(document, 200000)
70
+
68
71
  model_name = os.getenv("DOCUMENT_QA_MODEL_NAME", "deepseek/deepseek-chat-v3-0324")
69
72
  prompt = PROMPT.format(question=question, document=document)
70
73
  content = await llm_acall(model_name=model_name, prompt=prompt)
@@ -0,0 +1,151 @@
1
+ import re
2
+ import subprocess
3
+ import shutil
4
+ import tempfile
5
+ import json
6
+ from pathlib import Path
7
+
8
+
9
+ from academia_mcp.files import get_workspace_dir, DEFAULT_LATEX_TEMPLATES_DIR_PATH
10
+
11
+
12
+ def get_latex_templates_list() -> str:
13
+ """
14
+ Get the list of available latex templates.
15
+ Always use one of the templates from the list.
16
+
17
+ Returns a JSON list serialized to a string.
18
+ Use `json.loads` to deserialize the result.
19
+ """
20
+ return json.dumps([str(path.name) for path in DEFAULT_LATEX_TEMPLATES_DIR_PATH.glob("*")])
21
+
22
+
23
+ def get_latex_template(template_name: str) -> str:
24
+ """
25
+ Get the latex template by name.
26
+
27
+ Returns a JSON object serialized to a string.
28
+ Use `json.loads` to deserialize the result.
29
+ The structure is: {"template": "...", "style": "..."}
30
+
31
+ Args:
32
+ template_name: The name of the latex template.
33
+ """
34
+ template_dir_path = DEFAULT_LATEX_TEMPLATES_DIR_PATH / template_name
35
+ if not template_dir_path.exists():
36
+ raise FileNotFoundError(
37
+ f"Template {template_name} not found in {DEFAULT_LATEX_TEMPLATES_DIR_PATH}"
38
+ )
39
+ template_path = template_dir_path / f"{template_name}.tex"
40
+ style_path = template_dir_path / f"{template_name}.sty"
41
+ if not template_path.exists():
42
+ raise FileNotFoundError(f"Template file {template_path} not found in {template_dir_path}")
43
+ if not style_path.exists():
44
+ raise FileNotFoundError(f"Style file {style_path} not found in {template_dir_path}")
45
+ return json.dumps({"template": template_path.read_text(), "style": style_path.read_text()})
46
+
47
+
48
+ def compile_latex_from_file(
49
+ input_filename: str, output_filename: str = "output.pdf", timeout: int = 60
50
+ ) -> str:
51
+ """
52
+ Compile a latex file.
53
+
54
+ Returns a string with the result of the compilation.
55
+
56
+ Args:
57
+ input_filename: The path to the latex file.
58
+ output_filename: The path to the output pdf file.
59
+ timeout: The timeout for the compilation. 60 seconds by default.
60
+ """
61
+ with open(input_filename, "r", encoding="utf-8") as file:
62
+ latex_code = file.read()
63
+ return compile_latex_from_str(latex_code, output_filename, timeout)
64
+
65
+
66
+ def compile_latex_from_str(
67
+ latex_code: str, output_filename: str = "output.pdf", timeout: int = 60
68
+ ) -> str:
69
+ """
70
+ Compile a latex code.
71
+
72
+ Returns a string with the result of the compilation.
73
+
74
+ Args:
75
+ latex_code: The latex code to compile.
76
+ output_filename: The path to the output pdf file.
77
+ timeout: The timeout for the compilation. 60 seconds by default.
78
+ """
79
+ if shutil.which("pdflatex") is None:
80
+ return "pdflatex is not installed or not found in PATH."
81
+
82
+ destination_name = (
83
+ output_filename if output_filename.lower().endswith(".pdf") else f"{output_filename}.pdf"
84
+ )
85
+
86
+ try:
87
+ with tempfile.TemporaryDirectory(
88
+ dir=str(get_workspace_dir()), prefix="temp_latex_"
89
+ ) as temp_dir:
90
+ temp_dir_path = Path(temp_dir)
91
+ tex_filename = "temp.tex"
92
+ pdf_filename = "temp.pdf"
93
+ tex_file_path = temp_dir_path / tex_filename
94
+ tex_file_path.write_text(latex_code, encoding="utf-8")
95
+
96
+ # Detect and copy local .sty packages referenced by \usepackage{...}
97
+ # Supports optional arguments: \usepackage[opts]{pkgA,pkgB}
98
+ try:
99
+ package_names: set[str] = set()
100
+ for match in re.finditer(r"\\usepackage(?:\[[^\]]*\])?\{([^}]+)\}", latex_code):
101
+ for name in match.group(1).split(","):
102
+ pkg = name.strip()
103
+ if pkg:
104
+ package_names.add(pkg)
105
+
106
+ for pkg in package_names:
107
+ sty_name = f"{pkg}.sty"
108
+ for candidate in DEFAULT_LATEX_TEMPLATES_DIR_PATH.rglob(sty_name):
109
+ shutil.copyfile(candidate, temp_dir_path / sty_name)
110
+ break
111
+ except Exception:
112
+ pass
113
+
114
+ try:
115
+ subprocess.run(
116
+ [
117
+ "pdflatex",
118
+ "-interaction=nonstopmode",
119
+ tex_filename,
120
+ ],
121
+ cwd=str(temp_dir_path),
122
+ check=True,
123
+ capture_output=True,
124
+ text=True,
125
+ timeout=timeout,
126
+ )
127
+ except subprocess.TimeoutExpired:
128
+ return f"Compilation timed out after {timeout} seconds"
129
+ except subprocess.CalledProcessError as e:
130
+ combined_output = (e.stdout or "") + "\n" + (e.stderr or "")
131
+ error_lines = [
132
+ line
133
+ for line in combined_output.split("\n")
134
+ if ("error" in line.lower() or "!" in line)
135
+ ]
136
+ if error_lines:
137
+ return "Compilation failed. LaTeX errors:\n" + "\n".join(error_lines)
138
+ return f"Compilation failed. Full LaTeX output:\n{combined_output}"
139
+
140
+ pdf_path = temp_dir_path / pdf_filename
141
+ output_pdf_path = Path(get_workspace_dir()) / destination_name
142
+
143
+ if pdf_path.exists():
144
+ shutil.move(str(pdf_path), str(output_pdf_path))
145
+ return f"Compilation successful! PDF file saved as {destination_name}"
146
+
147
+ return (
148
+ "Compilation completed, but PDF file was not created. Check LaTeX code for errors."
149
+ )
150
+ except Exception as e:
151
+ return f"Compilation failed due to an unexpected error: {e}"
@@ -11,6 +11,17 @@ EXA_CONTENTS_URL = "https://api.exa.ai/contents"
11
11
  AVAILABLE_PROVIDERS = ("basic", "exa")
12
12
 
13
13
 
14
+ def _exa_visit_webpage(url: str) -> str:
15
+ key = os.getenv("EXA_API_KEY", "")
16
+ assert key, "Error: EXA_API_KEY is not set and no api_key was provided"
17
+ payload = {
18
+ "urls": [url],
19
+ "text": True,
20
+ }
21
+ response = post_with_retries(EXA_CONTENTS_URL, payload=payload, api_key=key)
22
+ return json.dumps(response.json()["results"][0])
23
+
24
+
14
25
  def visit_webpage(url: str, provider: Optional[str] = "basic") -> str:
15
26
  """
16
27
  Visit a webpage and return the content.
@@ -28,17 +39,17 @@ def visit_webpage(url: str, provider: Optional[str] = "basic") -> str:
28
39
  ), f"Invalid provider: {provider}. Available providers: {AVAILABLE_PROVIDERS}"
29
40
 
30
41
  if provider == "exa":
31
- key = os.getenv("EXA_API_KEY", "")
32
- assert key, "Error: EXA_API_KEY is not set and no api_key was provided"
33
- payload = {
34
- "urls": [url],
35
- "text": True,
36
- }
37
- response = post_with_retries(EXA_CONTENTS_URL, payload=payload, api_key=key)
38
- return json.dumps(response.json()["results"][0])
42
+ return _exa_visit_webpage(url)
39
43
 
40
44
  assert provider == "basic"
41
45
  response = get_with_retries(url)
46
+ content_type = response.headers.get("content-type", "").lower()
47
+ if not content_type or (not content_type.startswith("text/") and "html" not in content_type):
48
+ if os.getenv("EXA_API_KEY"):
49
+ return _exa_visit_webpage(url)
50
+ return json.dumps(
51
+ {"id": url, "error": f"Unsupported content-type: {content_type or 'unknown'}"}
52
+ )
42
53
  markdown_content = markdownify(response.text).strip()
43
54
  markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
44
55
  return json.dumps({"id": url, "text": markdown_content})
@@ -17,7 +17,8 @@ def web_search(
17
17
  provider: Optional[str] = "tavily",
18
18
  ) -> str:
19
19
  """
20
- Search the web using Exa Search or Tavily and return normalized results.
20
+ Search the web using Exa Search, Brave Search or Tavily and return normalized results.
21
+ If the specified provider is not available, the function will try to use the next available provider.
21
22
 
22
23
  Returns a JSON object serialized to a string. The structure is: {"results": [...]}
23
24
  Every item in the "results" has at least the following fields: ("title", "url")
@@ -47,13 +48,15 @@ def web_search(
47
48
  provider = p
48
49
  break
49
50
 
51
+ result = {}
50
52
  if provider == "exa":
51
- return exa_web_search(query, limit)
53
+ result = json.loads(exa_web_search(query, limit))
52
54
  elif provider == "brave":
53
- return brave_web_search(query, limit)
54
-
55
- assert provider == "tavily"
56
- return tavily_web_search(query, limit)
55
+ result = json.loads(brave_web_search(query, limit))
56
+ elif provider == "tavily":
57
+ result = json.loads(tavily_web_search(query, limit))
58
+ result["search_provider"] = provider
59
+ return json.dumps(result, ensure_ascii=False)
57
60
 
58
61
 
59
62
  def tavily_web_search(query: str, limit: Optional[int] = 20) -> str:
academia_mcp/utils.py CHANGED
@@ -13,10 +13,11 @@ def post_with_retries(
13
13
  api_key: Optional[str] = None,
14
14
  timeout: int = 30,
15
15
  num_retries: int = 3,
16
+ backoff_factor: float = 3.0,
16
17
  ) -> requests.Response:
17
18
  retry_strategy = Retry(
18
19
  total=num_retries,
19
- backoff_factor=3,
20
+ backoff_factor=backoff_factor,
20
21
  status_forcelist=[429, 500, 502, 503, 504],
21
22
  allowed_methods=["POST"],
22
23
  )
@@ -24,6 +25,7 @@ def post_with_retries(
24
25
  session = requests.Session()
25
26
  adapter = requests.adapters.HTTPAdapter(max_retries=retry_strategy)
26
27
  session.mount("https://", adapter)
28
+ session.mount("http://", adapter)
27
29
 
28
30
  headers = {
29
31
  "x-api-key": api_key,
@@ -42,11 +44,12 @@ def get_with_retries(
42
44
  api_key: Optional[str] = None,
43
45
  timeout: int = 30,
44
46
  num_retries: int = 3,
47
+ backoff_factor: float = 3.0,
45
48
  params: Optional[Dict[str, Any]] = None,
46
49
  ) -> requests.Response:
47
50
  retry_strategy = Retry(
48
51
  total=num_retries,
49
- backoff_factor=30,
52
+ backoff_factor=backoff_factor,
50
53
  status_forcelist=[429, 500, 502, 503, 504],
51
54
  allowed_methods=["GET"],
52
55
  )
@@ -54,6 +57,7 @@ def get_with_retries(
54
57
  session = requests.Session()
55
58
  adapter = requests.adapters.HTTPAdapter(max_retries=retry_strategy)
56
59
  session.mount("https://", adapter)
60
+ session.mount("http://", adapter)
57
61
 
58
62
  headers = {}
59
63
  if api_key:
@@ -145,3 +149,19 @@ def extract_json(text: str) -> Any:
145
149
  def encode_prompt(template: str, **kwargs: Any) -> str:
146
150
  template_obj = Template(template)
147
151
  return template_obj.render(**kwargs).strip()
152
+
153
+
154
+ def truncate_content(
155
+ content: str,
156
+ max_length: int,
157
+ ) -> str:
158
+ disclaimer = (
159
+ f"\n\n..._This content has been truncated to stay below {max_length} characters_...\n\n"
160
+ )
161
+ half_length = max_length // 2
162
+ if len(content) <= max_length:
163
+ return content
164
+
165
+ prefix = content[:half_length]
166
+ suffix = content[-half_length:]
167
+ return prefix + disclaimer + suffix
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: academia-mcp
3
- Version: 1.2.2
3
+ Version: 1.4.0
4
4
  Summary: MCP server that provides different tools to search for scientific publications
5
5
  Author-email: Ilya Gusev <phoenixilya@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/IlyaGusev/academia_mcp
@@ -22,16 +22,11 @@ Requires-Dist: markdownify==0.14.1
22
22
  Requires-Dist: acl-anthology==0.5.2
23
23
  Requires-Dist: markdown==3.7.0
24
24
  Requires-Dist: types-markdown==3.7.0.20250322
25
- Requires-Dist: black==25.1.0
26
- Requires-Dist: mypy==1.16.0
27
- Requires-Dist: flake8==7.2.0
28
25
  Requires-Dist: huggingface-hub>=0.32.4
29
26
  Requires-Dist: fire>=0.7.0
30
- Requires-Dist: pytest>=8.4.1
31
27
  Requires-Dist: openai>=1.97.1
32
28
  Requires-Dist: jinja2>=3.1.6
33
29
  Requires-Dist: datasets>=4.0.0
34
- Requires-Dist: pytest-asyncio>=1.1.0
35
30
  Dynamic: license-file
36
31
 
37
32
  # Academia MCP
@@ -44,16 +39,26 @@ A collection of MCP tools related to the search of scientific papers:
44
39
  - Web search: Exa/Brave/Tavily
45
40
  - Page crawler
46
41
 
47
- Install:
42
+ ## Install
43
+
44
+ - Using pip (end users):
48
45
  ```
49
46
  pip3 install academia-mcp
50
47
  ```
51
48
 
49
+ - For development (uv + Makefile):
50
+ ```
51
+ uv venv .venv
52
+ make install
53
+ ```
54
+
55
+ ## Examples
52
56
  Comprehensive report screencast: https://www.youtube.com/watch?v=4bweqQcN6w8
53
57
 
54
58
  Single paper screencast: https://www.youtube.com/watch?v=IAAPMptJ5k8
55
59
 
56
- Claude Desktop config:
60
+
61
+ ## Claude Desktop config
57
62
  ```
58
63
  {
59
64
  "mcpServers": {
@@ -69,3 +74,41 @@ Claude Desktop config:
69
74
  }
70
75
  }
71
76
  ```
77
+
78
+ ## Running the server (CLI)
79
+
80
+ ```
81
+ uv run -m academia_mcp --transport streamable-http
82
+ ```
83
+
84
+ Notes:
85
+ - Transports supported: `stdio`, `sse`, `streamable-http`.
86
+ - Host/port are used for HTTP transports; for `stdio` they are ignored.
87
+
88
+ ## Makefile targets
89
+
90
+ - `make install`: install the package in editable mode with uv.
91
+ - `make validate`: run black, flake8, and mypy (strict).
92
+ - `make test`: run the test suite with pytest.
93
+ - `make publish`: build and publish using uv.
94
+
95
+ ## Environment variables
96
+
97
+ Set as needed depending on which tools you use:
98
+
99
+ - `TAVILY_API_KEY`: enables Tavily in `web_search`.
100
+ - `EXA_API_KEY`: enables Exa in `web_search` and `visit_webpage`.
101
+ - `BRAVE_API_KEY`: enables Brave in `web_search`.
102
+ - `OPENROUTER_API_KEY`: required for `document_qa`.
103
+ - `BASE_URL`: override OpenRouter base URL for `document_qa` and bitflip tools.
104
+ - `DOCUMENT_QA_MODEL_NAME`: override default model for `document_qa`.
105
+ - `BITFLIP_MODEL_NAME`: override default model for bitflip tools.
106
+ - `WORKSPACE_DIR`: directory for generated files (PDFs, temp artifacts).
107
+
108
+ ## md_to_pdf requirements
109
+
110
+ The `md_to_pdf` tool invokes `pdflatex`. Ensure a LaTeX distribution is installed and `pdflatex` is on PATH. On Debian/Ubuntu:
111
+
112
+ ```
113
+ sudo apt install texlive-latex-base texlive-fonts-recommended texlive-latex-extra texlive-science
114
+ ```
@@ -0,0 +1,25 @@
1
+ academia_mcp/__init__.py,sha256=2Ru2I5u4cE7DrkkAsibDUEF1K6sYtqppb9VyFrRoQKI,94
2
+ academia_mcp/__main__.py,sha256=rcmsOtJd3SA82exjrcGBuxuptcoxF8AXI7jNjiVq2BY,59
3
+ academia_mcp/files.py,sha256=tvt3OPr5q6pAPCZ0XvRHHL9ZWuTXINRZvqjeRFmx5YE,815
4
+ academia_mcp/llm.py,sha256=o84FQNSbjjVSk9DlvFXWsUDiz5IOaavYU6kOqnPEG7E,1071
5
+ academia_mcp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ academia_mcp/server.py,sha256=FRrPAacAPs1IZ3LRKDFZi7copAqzy_aPGYd2RLsA01U,2974
7
+ academia_mcp/utils.py,sha256=P9U3RjYzcztE0KxXvJSy5wSBaUg2CM9tpByljYrsrl4,4607
8
+ academia_mcp/tools/__init__.py,sha256=u_6HkChV2P46zXxGp92s1cTSjkkd42udhCM3BFDYQ_c,1137
9
+ academia_mcp/tools/anthology_search.py,sha256=rhFpJZqGLABgr0raDuH0CARBiAJNJtEI4dlMrKNHfDQ,7669
10
+ academia_mcp/tools/arxiv_download.py,sha256=soa9nPDHV1-ZgTLtqh-Fj69WkRsrb1hRKouWDa2ePng,11269
11
+ academia_mcp/tools/arxiv_search.py,sha256=pzM18qrF3QL03A53w003kE7hQi3s3QKtjgw0m7K88UY,8355
12
+ academia_mcp/tools/bitflip.py,sha256=u0hSOPWbnCDu2EbA_RkueX496SvTKz9QhZcXugshSfI,10949
13
+ academia_mcp/tools/document_qa.py,sha256=04pJpiYCg27EFiZhfmTaMjeobu8SMT0Dls7OAFDoH00,2392
14
+ academia_mcp/tools/hf_datasets_search.py,sha256=KiBkqT4rXjEN4oc1AWZOPnqN_Go90TQogY5-DUm3LQo,2854
15
+ academia_mcp/tools/latex.py,sha256=rM6Xm4dXkpbhOMuxx-lK83dzCEAs_bWhRaK44hyGwuU,5639
16
+ academia_mcp/tools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ academia_mcp/tools/s2_citations.py,sha256=dqrBp76RrX1zH2XzcMAoWBbvbtyhxLeF-xnqOKD_JiM,4852
18
+ academia_mcp/tools/visit_webpage.py,sha256=OZdqDkVPIbANyFw5o5jIjU5Rr_dolxrGDs63Ud-GmRM,1966
19
+ academia_mcp/tools/web_search.py,sha256=mobKm4iqKppn8pduZYMzWRo1MQBjkAqmMtrFLI5XY2Y,6296
20
+ academia_mcp-1.4.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
21
+ academia_mcp-1.4.0.dist-info/METADATA,sha256=6A2AjFm3IplORaP02xXTgBdTNY00Bz56nU5t1w5gNg8,3172
22
+ academia_mcp-1.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
23
+ academia_mcp-1.4.0.dist-info/entry_points.txt,sha256=gxkiKJ74w2FwJpSECpjA3XtCfI5ZfrM6N8cqnwsq4yY,51
24
+ academia_mcp-1.4.0.dist-info/top_level.txt,sha256=CzGpRFsRRJRqWEb1e3SUlcfGqRzOxevZGaJWrtGF8W0,13
25
+ academia_mcp-1.4.0.dist-info/RECORD,,
@@ -1,404 +0,0 @@
1
- import markdown
2
- import re
3
- import os
4
- import subprocess
5
- import shutil
6
- import xml.dom.minidom
7
- import xml.etree.ElementTree as etree
8
- from typing import Optional, Any
9
-
10
- from markdown.core import Markdown
11
-
12
- from academia_mcp.files import get_workspace_dir
13
-
14
-
15
- START_SINGLE_QUOTE_RE = re.compile(r"(^|\s|\")'")
16
- START_DOUBLE_QUOTE_RE = re.compile(r"(^|\s|'|`)\"")
17
- END_DOUBLE_QUOTE_RE = re.compile(r'"(,|\.|\s|$)')
18
-
19
-
20
- MAIN_TEMPLATE = """\\documentclass{{article}}
21
- \\usepackage[utf8]{{inputenc}}
22
- \\usepackage[T1]{{fontenc}}
23
- \\usepackage{{textcomp}}
24
- \\usepackage{{amsmath}}
25
- \\usepackage{{float}}
26
- \\usepackage{{graphicx}}
27
- \\usepackage{{enumitem}}
28
- \\usepackage{{quoting}}
29
- \\usepackage{{booktabs}}
30
- \\usepackage{{caption}}
31
- \\usepackage{{siunitx}}
32
- \\sisetup{{
33
- group-separator = {{,}},
34
- output-decimal-marker = {{.}}
35
- }}
36
- \\usepackage{{hyperref}}
37
-
38
- \\author{{Holosophos}}
39
-
40
- \\begin{{document}}
41
-
42
- {latex_content}
43
-
44
- \\end{{document}}"""
45
-
46
-
47
- IMAGE_TEMPLATE = """\\begin{{figure}}[H]
48
- \\centering
49
- \\includegraphics[width=\\linewidth]{{{src}}}
50
- \\caption{{{alt}}}
51
- \\end{{figure}}"""
52
-
53
-
54
- TABLE_TEMPLATE = """
55
- \\begin{{table}}[h]
56
- \\begin{{tabular}}{{{descriptor}}}
57
- {core}
58
- \\hline
59
- \\end{{tabular}}
60
- \\\\[5pt]
61
- \\caption{{{caption}}}
62
- \\end{{table}}
63
- """
64
-
65
- ITEMIZE_TEMPLATE = """
66
- \\begin{{itemize}}
67
- {content}
68
- \\end{{itemize}}
69
- """
70
-
71
- QUOTE_TEMPLATE = """
72
- \\begin{{quotation}}
73
- {content}
74
- \\end{{quotation}}
75
- """
76
-
77
- VERBATIM_TEMPLATE = """
78
- \\begin{{verbatim}}
79
- {content}
80
- \\end{{verbatim}}
81
- """
82
-
83
-
84
- MAKETITLE = """
85
- % ----------------------------------------------------------------
86
- \\maketitle
87
- % ----------------------------------------------------------------
88
- """
89
-
90
-
91
- def inline_html_latex(text: str) -> str:
92
- out = text
93
- if re.search(r"&ldquo;.*?&rdquo;", text, flags=re.DOTALL):
94
- out = out.replace("&ldquo;", "\\enquote{").replace("&rdquo;", "}")
95
- if re.search(r"&lsquo;.*?&rsquo;", text, flags=re.DOTALL):
96
- out = out.replace("&lsquo;", "\\enquote{").replace("&rsquo;", "}")
97
- if re.search(r"&ldquo;.*?&ldquo;", text, flags=re.DOTALL):
98
- out = out.replace("&ldquo;", "\\enquote{", 1).replace("&ldquo;", "}", 1)
99
- if re.search(r"&laquo;.*?&raquo;", text, flags=re.DOTALL):
100
- out = out.replace("&laquo;", "\\enquote{").replace("&raquo;", "}")
101
- out = out.replace("...", "\\dots")
102
- out = out.replace("&hellip;", "\\dots")
103
- out = out.replace("&ndash;", "--")
104
- out = out.replace("&mdash;", "---")
105
- out = out.replace("\\|", "|")
106
- return out
107
-
108
-
109
- def unescape_html_entities(text: str) -> str:
110
- mapping = {
111
- "&amp;": "&",
112
- "&lt;": "<",
113
- "&gt;": ">",
114
- "&quot;": '"',
115
- }
116
- for k, v in mapping.items():
117
- text = text.replace(k, v)
118
- return text
119
-
120
-
121
- def escape_latex_entities(text: str) -> str:
122
- out = unescape_html_entities(text)
123
- out = out.replace("%", "\\%")
124
- out = out.replace("&", "\\&")
125
- out = out.replace("#", "\\#")
126
- out = START_SINGLE_QUOTE_RE.sub(r"\g<1>`", out)
127
- out = START_DOUBLE_QUOTE_RE.sub(r"\g<1>``", out)
128
- out = END_DOUBLE_QUOTE_RE.sub(r"''\g<1>", out)
129
- return out
130
-
131
-
132
- class LaTeXExtension(markdown.Extension):
133
- def __init__(self, configs: Optional[Any] = None) -> None:
134
- self.reset()
135
-
136
- def extendMarkdown(self, md: Markdown) -> None:
137
- self.md = md
138
- latex_tp = LaTeXTreeProcessor()
139
- math_pp = MathTextPostProcessor()
140
- table_pp = TableTextPostProcessor()
141
- image_pp = ImageTextPostProcessor()
142
- link_pp = LinkTextPostProcessor()
143
- unescape_html_pp = UnescapeHtmlTextPostProcessor()
144
-
145
- md.treeprocessors.register(latex_tp, "latex", 20)
146
- md.postprocessors.register(unescape_html_pp, "unescape_html", 20)
147
- md.postprocessors.register(math_pp, "math", 20)
148
- md.postprocessors.register(image_pp, "image", 20)
149
- md.postprocessors.register(table_pp, "table", 20)
150
- md.postprocessors.register(link_pp, "link", 20)
151
-
152
- def reset(self) -> None:
153
- pass
154
-
155
-
156
- class LaTeXTreeProcessor(markdown.treeprocessors.Treeprocessor):
157
- def run(self, doc: etree.Element) -> None:
158
- latex_text = self.tolatex(doc)
159
- doc.clear()
160
- latex_node = etree.Element("plaintext")
161
- latex_node.text = latex_text
162
- doc.append(latex_node)
163
-
164
- def tolatex(self, ournode: etree.Element) -> str:
165
- buf = ""
166
- subcontent = ""
167
-
168
- if ournode.text:
169
- subcontent += escape_latex_entities(ournode.text)
170
-
171
- for child in list(ournode):
172
- subcontent += self.tolatex(child)
173
-
174
- tag = ournode.tag
175
- if tag == "h1":
176
- buf += "\n\\title{%s}\n" % subcontent
177
- buf += MAKETITLE
178
- elif tag == "h2":
179
- buf += "\n\n\\section{%s}\n" % subcontent
180
- elif tag == "h3":
181
- buf += "\n\n\\subsection{%s}\n" % subcontent
182
- elif tag == "h4":
183
- buf += "\n\\subsubsection{%s}\n" % subcontent
184
- elif tag == "hr":
185
- buf += "\\noindent\\makebox[\\linewidth]{\\rule{\\linewidth}{0.4pt}}"
186
- elif tag == "ul":
187
- buf += ITEMIZE_TEMPLATE.format(content=subcontent.strip())
188
- elif tag == "ol":
189
- buf += " \\begin{enumerate}"
190
- if "start" in ournode.attrib:
191
- start = int(ournode.attrib["start"]) - 1
192
- buf += "\\setcounter{enumi}{" + str(start) + "}"
193
- buf += f"\n{subcontent}\n\\end{{enumerate}}"
194
- elif tag == "li":
195
- buf += "\n \\item %s" % subcontent.strip()
196
- elif tag == "blockquote":
197
- buf += QUOTE_TEMPLATE.format(content=subcontent.strip())
198
- elif tag == "pre":
199
- buf += VERBATIM_TEMPLATE.format(content=subcontent.strip())
200
- elif tag == "q":
201
- buf += "`%s'" % subcontent.strip()
202
- elif tag == "p":
203
- buf += "\n%s\n" % subcontent.strip()
204
- elif tag == "sup":
205
- buf += "\\footnote{%s}" % subcontent.strip()
206
- elif tag == "strong":
207
- buf += "\\textbf{%s}" % subcontent.strip()
208
- elif tag == "em":
209
- buf += "\\emph{%s}" % subcontent.strip()
210
- elif tag == "table":
211
- buf += "\n\n<table>%s</table>\n\n" % subcontent
212
- elif tag == "thead":
213
- buf += "<thead>%s</thead>" % subcontent
214
- elif tag == "tbody":
215
- buf += "<tbody>%s</tbody>" % subcontent
216
- elif tag == "tr":
217
- buf += "<tr>%s</tr>" % subcontent
218
- elif tag == "th":
219
- buf += "<th>%s</th>" % subcontent
220
- elif tag == "td":
221
- buf += "<td>%s</td>" % subcontent
222
- elif tag == "img":
223
- buf += '<img src="%s" alt="%s" />' % (
224
- ournode.get("src"),
225
- ournode.get("alt"),
226
- )
227
- elif tag == "a":
228
- href = ournode.get("href")
229
- assert href
230
- buf += '<a href="%s">%s</a>' % (
231
- escape_latex_entities(href),
232
- subcontent,
233
- )
234
- else:
235
- buf = subcontent
236
-
237
- if ournode.tail:
238
- buf += escape_latex_entities(ournode.tail)
239
-
240
- return buf
241
-
242
-
243
- class Table2Latex:
244
- def convert_markdown_table(self, instr: str) -> str:
245
- lines = instr.split("\n")
246
- headers = lines[0].strip("|").split("|")
247
- cols = len(headers)
248
- buf = (
249
- "\\begin{table}[h]\n\\centering\n\\begin{tabular}{|"
250
- + "|".join(["l"] * cols)
251
- + "|}\n\\hline\n"
252
- )
253
- buf += (
254
- " & ".join([f"\\textbf{{{header.strip()}}}" for header in headers]) + " \\\\\n\\hline\n"
255
- )
256
- for line in lines[2:]:
257
- cells = line.strip("|").split("|")
258
- buf += " & ".join([cell.strip() for cell in cells]) + " \\\\\n\\hline\n"
259
- buf += "\\end{tabular}\n\\end{table}"
260
- return buf
261
-
262
-
263
- class Img2Latex:
264
- def convert(self, instr: str) -> str:
265
- dom = xml.dom.minidom.parseString(instr)
266
- img = dom.documentElement
267
- assert img is not None
268
- src = img.getAttribute("src")
269
- alt = img.getAttribute("alt")
270
- return IMAGE_TEMPLATE.format(src=src, alt=alt)
271
-
272
-
273
- class Link2Latex:
274
- def convert(self, instr: str) -> str:
275
- dom = xml.dom.minidom.parseString(instr)
276
- link = dom.documentElement
277
- assert link is not None
278
- href = link.getAttribute("href")
279
- matches = re.search(r">([^<]+)", instr)
280
- desc = ""
281
- if matches:
282
- desc = matches.group(1)
283
- return r"\href{%s}{%s}" % (href, desc) if href != desc else r"\url{%s}" % href
284
-
285
-
286
- class ImageTextPostProcessor(markdown.postprocessors.Postprocessor):
287
- def run(self, instr: str) -> str:
288
- converter = Img2Latex()
289
- new_blocks = []
290
- for block in instr.split("\n\n"):
291
- stripped = block.strip()
292
- if stripped.startswith("<img"):
293
- stripped = re.sub(r"<\/?plaintext[^>]*>", "", stripped, flags=re.IGNORECASE)
294
- new_blocks.append(converter.convert(stripped).strip())
295
- else:
296
- new_blocks.append(block)
297
- return "\n\n".join(new_blocks)
298
-
299
-
300
- class LinkTextPostProcessor(markdown.postprocessors.Postprocessor):
301
- def run(self, instr: str) -> str:
302
- converter = Link2Latex()
303
- new_blocks = []
304
- for block in instr.split("\n\n"):
305
- stripped = block.strip()
306
- matches = re.findall(r"<a[^>]*>[^<]+</a>", stripped)
307
- if matches:
308
- for match in matches:
309
- stripped = stripped.replace(match, converter.convert(match).strip())
310
- new_blocks.append(stripped)
311
- else:
312
- new_blocks.append(block)
313
- return "\n\n".join(new_blocks)
314
-
315
-
316
- class UnescapeHtmlTextPostProcessor(markdown.postprocessors.Postprocessor):
317
- def run(self, text: str) -> str:
318
- return unescape_html_entities(inline_html_latex(text))
319
-
320
-
321
- class MathTextPostProcessor(markdown.postprocessors.Postprocessor):
322
- def run(self, instr: str) -> str:
323
- instr = re.sub(r"\$\$([^\$]*)\$\$", r"\\[\1\\]", instr)
324
- instr = re.sub(r"\$([^\$]*)\$", r"\\(\1\\)", instr)
325
- instr = instr.replace("\\lt", "<").replace(" * ", " \\cdot ").replace("\\del", "\\partial")
326
- return instr
327
-
328
-
329
- class TableTextPostProcessor(markdown.postprocessors.Postprocessor):
330
- def run(self, instr: str) -> str:
331
- converter = Table2Latex()
332
- new_blocks = []
333
- for block in instr.split("\n\n"):
334
- stripped = block.strip()
335
- if re.match(r"\|.*\|", stripped): # Check for Markdown table
336
- new_blocks.append(converter.convert_markdown_table(stripped).strip())
337
- else:
338
- new_blocks.append(block)
339
- return "\n\n".join(new_blocks)
340
-
341
-
342
- def convert_md_to_latex(md_content: str) -> str:
343
- md = markdown.Markdown(extensions=[LaTeXExtension()])
344
- latex_content = md.convert(md_content)
345
- latex_content = re.sub(r"<\/?plaintext[^>]*>", "", latex_content, flags=re.IGNORECASE)
346
- return MAIN_TEMPLATE.format(latex_content=latex_content)
347
-
348
-
349
- def md_to_pdf(markdown_text: str, output_filename: str = "output") -> str:
350
- """
351
- Convert Markdown to PDF via LaTeX.
352
-
353
- Args:
354
- markdown_text: Markdown text
355
- output_filename: Output filename (without extension)
356
-
357
- Returns:
358
- Message about the compilation result
359
- """
360
-
361
- latex_code = convert_md_to_latex(markdown_text)
362
-
363
- temp_dir = get_workspace_dir() / "temp_latex"
364
- temp_dir.mkdir(parents=True, exist_ok=True)
365
-
366
- tex_file_path = temp_dir / "temp.tex"
367
- with open(tex_file_path, "w", encoding="utf-8") as f:
368
- f.write(latex_code)
369
-
370
- try:
371
- subprocess.run(
372
- [
373
- "pdflatex",
374
- "-interaction=nonstopmode",
375
- "-output-directory",
376
- temp_dir,
377
- tex_file_path,
378
- ],
379
- check=True,
380
- stdout=subprocess.PIPE,
381
- stderr=subprocess.PIPE,
382
- timeout=30,
383
- )
384
-
385
- except subprocess.TimeoutExpired:
386
- return "Compilation timed out after 30 seconds"
387
- except subprocess.CalledProcessError as e:
388
- error_msg = e.stdout.decode("utf-8")
389
- error_lines = [
390
- line for line in error_msg.split("\n") if "error" in line.lower() or "!" in line
391
- ]
392
- if error_lines:
393
- return "Compilation failed. LaTeX errors:\n" + "\n".join(error_lines)
394
- return f"Compilation failed. Full LaTeX output:\n{error_msg}"
395
-
396
- pdf_path = os.path.join(temp_dir, "temp.pdf")
397
- output_pdf_path = os.path.join(get_workspace_dir(), f"{output_filename}.pdf")
398
-
399
- if os.path.exists(pdf_path):
400
- shutil.move(pdf_path, output_pdf_path)
401
- shutil.rmtree(temp_dir, ignore_errors=True)
402
- return f"Compilation successful! PDF file saved as {output_filename}.pdf"
403
-
404
- return "Compilation completed, but PDF file was not created. Check LaTeX code for errors."
@@ -1,25 +0,0 @@
1
- academia_mcp/__init__.py,sha256=2Ru2I5u4cE7DrkkAsibDUEF1K6sYtqppb9VyFrRoQKI,94
2
- academia_mcp/__main__.py,sha256=rcmsOtJd3SA82exjrcGBuxuptcoxF8AXI7jNjiVq2BY,59
3
- academia_mcp/files.py,sha256=hI5dj4h0fX8V3DXKI_C8vs1fte2uc9gsBXC6prLV4o4,745
4
- academia_mcp/llm.py,sha256=o84FQNSbjjVSk9DlvFXWsUDiz5IOaavYU6kOqnPEG7E,1071
5
- academia_mcp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- academia_mcp/server.py,sha256=q9bhacVm-8uuIMc_xSeymmVaIB8pQCqfTQx5GU8hhpM,2492
7
- academia_mcp/utils.py,sha256=tkHBho-NfzAR8rplFaiRYq4sBmQ9V3JPjDJTDrz58Xs,4041
8
- academia_mcp/tools/__init__.py,sha256=8_8QWPRYmPiUjdiNrQilEEnCRR-UBU7g-56jT52V3VQ,934
9
- academia_mcp/tools/anthology_search.py,sha256=_5s8EzdV7NQD_F3bjVH4XlKKHOJlFtWlQVrPbODuc3I,7847
10
- academia_mcp/tools/arxiv_download.py,sha256=xanzt77TZBQRngzGbKCRz4Hp-Mwfe_q-46eRW23TpVs,11219
11
- academia_mcp/tools/arxiv_search.py,sha256=pzM18qrF3QL03A53w003kE7hQi3s3QKtjgw0m7K88UY,8355
12
- academia_mcp/tools/bitflip.py,sha256=u0hSOPWbnCDu2EbA_RkueX496SvTKz9QhZcXugshSfI,10949
13
- academia_mcp/tools/document_qa.py,sha256=lWtzRNFKwQpQO8vPNvYYbNnGh3LsBmGl6f9vSRIuqaw,2245
14
- academia_mcp/tools/hf_datasets_search.py,sha256=KiBkqT4rXjEN4oc1AWZOPnqN_Go90TQogY5-DUm3LQo,2854
15
- academia_mcp/tools/md_to_pdf.py,sha256=Ovc_-8j7gIZNEM1d0ZDH-8qbtfZLSaNmCm5DQjrtM0k,12810
16
- academia_mcp/tools/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
- academia_mcp/tools/s2_citations.py,sha256=dqrBp76RrX1zH2XzcMAoWBbvbtyhxLeF-xnqOKD_JiM,4852
18
- academia_mcp/tools/visit_webpage.py,sha256=0zAZYeQxPDu0OjgAAvbMLZh0ttaS5q-_4WhgsEPrbsI,1542
19
- academia_mcp/tools/web_search.py,sha256=P74HF5agF-cWOGUYmrDcr_R-Ay3xz9fNdhFov8vtt9o,6025
20
- academia_mcp-1.2.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
21
- academia_mcp-1.2.2.dist-info/METADATA,sha256=SC1JQUbH4sbFFZFcuTeC-iwEVIhMbQqXlSL2sB6riqM,1899
22
- academia_mcp-1.2.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
23
- academia_mcp-1.2.2.dist-info/entry_points.txt,sha256=gxkiKJ74w2FwJpSECpjA3XtCfI5ZfrM6N8cqnwsq4yY,51
24
- academia_mcp-1.2.2.dist-info/top_level.txt,sha256=CzGpRFsRRJRqWEb1e3SUlcfGqRzOxevZGaJWrtGF8W0,13
25
- academia_mcp-1.2.2.dist-info/RECORD,,