Coverage for src/scixplorer/mcp_server.py: 98%

293 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-18 23:06 +0000

1"""A Model Context Protocol (MCP) server for SciX, run by ``scix --mcp``. 

2 

3It gives an assistant such as Claude the things scixplorer does that a plain 

4search API cannot: a search that reads plain words and names (journals, 

5institutions and Unified Astronomy Thesaurus concepts are resolved locally, 

6without the assistant having to know their identifiers), and says how it read 

7them; plus documents, exports, citation metrics and SciX libraries. 

8 

9The tools are the methods of :class:`Tools`, which return plain dicts and can 

10be called without a server; :func:`build` registers them on an ``MCPServer``, 

11and :func:`serve` runs it on standard input and output. 

12 

13This module needs the ``mcp`` package, version 2 or later, which is not 

14installed with scixplorer: install ``scixplorer[mcp]``. 

15""" 

16 

17from __future__ import annotations 

18 

19import functools 

20import re 

21from collections.abc import Callable 

22from typing import Annotated, Any, Literal, TypeVar 

23 

24from mcp.server.mcpserver import MCPServer 

25from mcp.server.mcpserver.exceptions import ToolError 

26from mcp.types import ToolAnnotations 

27from pydantic import Field 

28 

29from . import __version__ 

30from .cli import default_sort 

31from .cli.interpret import Interpretation, Reading, _identifier, _journals, _thesaurus, interpret 

32from .cli.output import FIELDS, SORTS, abstract_of, authors_line, page_url, pdf_url, reference, title_of 

33from .cli.session import Session 

34from .client import Client, get_default_client 

35from .exceptions import APIError, SciXError 

36from .models.affiliation import Affiliation 

37from .models.document import Document 

38from .models.journal import Journal 

39from .models.library import Library 

40from .models.planetary import PlanetaryFeature 

41from .models.uat import UATConcept 

42from .search import to_solr 

43from .services import export as export_service 

44from .services.metrics import metrics as metrics_service 

45 

46__all__ = ["INSTRUCTIONS", "Tools", "build", "serve"] 

47 

48#: The most documents one call hands to the export, metrics and library services. 

49MAX_DOCUMENTS = 2000 

50 

51SortName = Literal["date", "citations", "reads", "relevance", "oldest", "author"] 

52 

53ExportFormat = Literal[ 

54 "bibtex", "bibtexabs", "aastex", "ads", "endnote", "medlars", "procite", "refworks", "ris", 

55 "icarus", "mnras", "soph", "ieee", "dcxml", "refxml", "refabsxml", "votable", 

56] # fmt: skip 

57 

58#: What the server tells an assistant when it connects. 

59INSTRUCTIONS = """\ 

60Tools for SciX (Science Explorer, the successor to NASA/ADS): the literature of astronomy, physics, \ 

61planetary and earth science. 

62 

63Start with `search`. Its query may be plain words: it reads capitalised words as author surnames, \ 

64four-digit numbers as years, journal names and Unified Astronomy Thesaurus concepts as what they are, \ 

65and returns `read_as`, which says how each word was understood. If that is not what was meant, name \ 

66the fields (author:"Kewley, L" year:2015-2020 journal:ApJ title:"..."). `explain_search` shows the \ 

67reading without searching. `resolve` finds the identifier of a journal, institution, concept or \ 

68planetary feature by name. 

69 

70Documents are identified by bibcode (such as 2019ApJ...880...16K). `get_document` gives one in full; \ 

71`export` gives BibTeX and other formats; `metrics` gives citation statistics. Libraries are the user's \ 

72saved collections on SciX: tools that create, change or delete them act on the user's account, so do \ 

73so only when asked. 

74""" 

75 

76_QUERY = """\ 

77What to search for, in plain words or with named fields; every part must match. \ 

78Capitalised words are author surnames (Kewley; "Kewley, L. J." with initials; ^Kewley or \ 

79"Kewley et al." for the first author). Four-digit numbers are years (2019, 2015-2020, "since 2020"). \ 

80A journal abbreviation or title is that journal, and numbers after it are volume and page \ 

81(ApJ 880 16). The name of a Unified Astronomy Thesaurus concept, written without quotes, is that \ 

82topic (exoplanets, hot jupiters). A bibcode, DOI, arXiv id or ORCID iD is that identifier. A phrase \ 

83in quotes, and any other word, is searched as text in title, abstract and keywords. \ 

84To be exact, name the field: author:"Kewley, L" first_author: title: abs: year:2015-2020 \ 

85journal:ApJ uat:<name or number> inst:"Harvard U" aff_id: orcid: doi: property:refereed \ 

86doctype:article database:astronomy, or any other SciX field. \ 

87Operators take a bibcode or a query: citations:2019ApJ...880...16K (documents citing it), \ 

88references: (documents it cites), similar:, trending:exoplanets, reviews:, useful:.\ 

89""" 

90 

91_LIBRARY = "The library: its id, or its exact name." 

92 

93_BIBCODES = f"Bibcodes of the documents (at most {MAX_DOCUMENTS})." 

94 

95_FROM_QUERY = "Instead of bibcodes: a search, read as by `search`, whose first `limit` results are used." 

96 

97_Method = TypeVar("_Method", bound=Callable[..., Any]) 

98 

99 

100def _tool(method: _Method) -> _Method: 

101 """Report the errors a caller can act on as tool errors, with their message. 

102 

103 Anything else is a fault in the server, and the MCP server hides its details. 

104 """ 

105 

106 @functools.wraps(method) 

107 def wrapper(*args: Any, **kwargs: Any) -> Any: 

108 try: 

109 return method(*args, **kwargs) 

110 except (SciXError, ValueError) as error: 

111 raise ToolError(str(error)) from error 

112 

113 return wrapper # type: ignore[return-value] 

114 

115 

116def _brief(document: Document, *, abstract: bool = False) -> dict[str, Any]: 

117 """A document in a few lines: enough to choose among results.""" 

118 data = document._data 

119 brief: dict[str, Any] = { 

120 "bibcode": data.get("bibcode"), 

121 "title": title_of(document), 

122 "authors": authors_line(document, 3), 

123 "year": data.get("year"), 

124 "publication": reference(document), 

125 "citations": data.get("citation_count") or 0, 

126 } 

127 if abstract: 

128 brief["abstract"] = abstract_of(document) 

129 return brief 

130 

131 

132def _library(library: Library) -> dict[str, Any]: 

133 modified = library.date_last_modified 

134 return { 

135 "id": library.id, 

136 "name": library.name, 

137 "description": library.description, 

138 "documents": library.num_documents, 

139 "public": library.public, 

140 "permission": library.permission, 

141 "owner": library.owner, 

142 "last_modified": modified.isoformat() if modified is not None else None, 

143 } 

144 

145 

146def _ranked(text: str, rows: list[Any], names: Callable[[Any], list[str]]) -> list[Any]: 

147 """``rows`` with those named exactly ``text`` first, then those whose name starts with it.""" 

148 wanted = text.strip().lower() 

149 

150 def rank(row: Any) -> int: 

151 lowered = [name.lower() for name in names(row) if name] 

152 if wanted in lowered: 

153 return 0 

154 return 1 if any(name.startswith(wanted) for name in lowered) else 2 

155 

156 return sorted(rows, key=rank) 

157 

158 

159class Tools: 

160 """What the server's tools do. Every method returns something JSON can hold. 

161 

162 :param client: the client to send requests with (default: the default client). 

163 """ 

164 

165 def __init__(self, client: Client | None = None) -> None: 

166 self._client = client 

167 self.session = Session(client) 

168 

169 @property 

170 def client(self) -> Client: 

171 return self._client if self._client is not None else get_default_client() 

172 

173 # Searching. 

174 

175 def _read(self, query: str, solr: bool = False) -> Interpretation: 

176 text = query.strip() 

177 if not text: 

178 raise ValueError("The query is empty: say what to search for.") 

179 if solr: 

180 return Interpretation(text, (Reading("query", text, text, Document.raw(text)),)) 

181 return interpret(text) 

182 

183 def _bibcodes(self, bibcodes: list[str] | None, query: str | None, limit: int) -> list[str]: 

184 """The documents a tool was given: bibcodes, or the first ``limit`` results of a search.""" 

185 if (bibcodes is None) == (query is None): 

186 raise ValueError("Give either bibcodes or query, not both and not neither.") 

187 if bibcodes is not None: 

188 found = list(dict.fromkeys(bibcode.strip() for bibcode in bibcodes if bibcode.strip())) 

189 if not found: 

190 raise ValueError("No bibcodes were given.") 

191 return found 

192 interpretation = self._read(query or "") 

193 found, _ = self.session.bibcodes(interpretation, default_sort(interpretation), limit=limit) 

194 if not found: 

195 raise ValueError(f"The search matched no documents (read as: {interpretation}).") 

196 return found 

197 

198 @_tool 

199 def search( 

200 self, 

201 query: Annotated[str, Field(description=_QUERY)], 

202 limit: Annotated[int, Field(ge=1, le=100, description="How many documents to return.")] = 10, 

203 offset: Annotated[int, Field(ge=0, description="How many documents to skip, to see the next page.")] = 0, 

204 sort: Annotated[ 

205 SortName | None, 

206 Field(description="The order. By default: citations if the query names a year, else date (newest first)."), 

207 ] = None, 

208 abstracts: Annotated[bool, Field(description="Include each document's abstract.")] = False, 

209 solr: Annotated[ 

210 bool, Field(description="Send the query to SciX as Solr syntax, exactly as written, without reading it.") 

211 ] = False, 

212 ) -> dict[str, Any]: 

213 """Search SciX (the successor to NASA/ADS) for papers and other documents. 

214 

215 Returns how the query was read (`read_as`), the Solr query sent, the 

216 number of documents that match (`total`) and the documents, each with 

217 its bibcode, title, first authors, year, publication and citation count. 

218 If nothing matches, the search is widened once (a surname is also 

219 searched as a word, a concept also as its words) and `note` says so. 

220 """ 

221 interpretation = self._read(query, solr) 

222 order = sort or default_sort(interpretation) 

223 note = None 

224 if offset: 

225 documents, total = self.session.fetch(interpretation, order, limit=limit, offset=offset) 

226 else: 

227 found = self.session.find(interpretation, order, limit=limit) 

228 documents, total = found.documents, found.total 

229 if found.widened: 

230 note = f"Nothing matched {interpretation}, so the search was widened." 

231 interpretation = found.interpretation 

232 result: dict[str, Any] = { 

233 "read_as": str(interpretation), 

234 "solr_query": to_solr(self.session.query(interpretation, order)), 

235 "sort": SORTS[order][2], 

236 "total": total, 

237 "offset": offset, 

238 "documents": [_brief(document, abstract=abstracts) for document in documents], 

239 } 

240 notes = [note, *interpretation.notes] if note else list(interpretation.notes) 

241 if notes: 

242 result["note"] = " ".join(notes) 

243 return result 

244 

245 @_tool 

246 def explain_search( 

247 self, 

248 query: Annotated[str, Field(description=_QUERY)], 

249 ) -> dict[str, Any]: 

250 """Show how `search` would read a query, piece by piece, and the Solr query it would send. 

251 

252 Nothing is sent to SciX. Use it to check a query before running it, or 

253 to learn the Solr syntax for something. 

254 """ 

255 interpretation = self._read(query) 

256 order = default_sort(interpretation) 

257 result: dict[str, Any] = { 

258 "read_as": [ 

259 {"typed": reading.source, "as": reading.kind, "meaning": reading.value} 

260 for reading in interpretation.readings 

261 ], 

262 "solr_query": to_solr(self.session.query(interpretation, order)), 

263 "sort": SORTS[order][2], 

264 } 

265 if interpretation.notes: 

266 result["note"] = " ".join(interpretation.notes) 

267 return result 

268 

269 @_tool 

270 def get_document( 

271 self, 

272 identifier: Annotated[ 

273 str, Field(description="A bibcode, DOI or arXiv identifier, or a link to the document on SciX, ADS or arXiv.") 

274 ], 

275 ) -> dict[str, Any]: 

276 """Get one document in full: all its authors, its abstract, keywords, identifiers and links.""" 

277 text = identifier.strip() 

278 if not text: 

279 raise ValueError("The identifier is empty.") 

280 reading = _identifier(text) 

281 expr = reading.expr if reading is not None and reading.kind != "orcid" else Document.identifier == text 

282 fields = (*FIELDS, "pubdate", "keyword", "uat", "reference_count", "read_count") 

283 document = Document.select(*fields).where(expr).limit(1).using(self.client).first() 

284 if document is None: 

285 raise ToolError(f"SciX has no document with the identifier {text!r}.") 

286 data = document._data 

287 authors = data.get("author") or [] 

288 date = data.get("pubdate") 

289 arxiv = [each for each in data.get("identifier") or [] if each.lower().startswith("arxiv:")] 

290 return { 

291 "bibcode": data.get("bibcode"), 

292 "title": title_of(document), 

293 "authors": authors[:50], 

294 "author_count": len(authors), 

295 "year": data.get("year"), 

296 "date": date.isoformat() if date is not None else None, 

297 "publication": data.get("pub"), 

298 "reference": reference(document), 

299 "type": data.get("doctype"), 

300 "refereed": "refereed" in (each.lower() for each in data.get("property") or []), 

301 "doi": (data.get("doi") or [None])[0], 

302 "arxiv": arxiv[0] if arxiv else None, 

303 "keywords": (data.get("keyword") or [])[:25], 

304 "uat_concepts": data.get("uat") or [], 

305 "abstract": abstract_of(document), 

306 "citations": data.get("citation_count") or 0, 

307 "references": data.get("reference_count") or 0, 

308 "reads": data.get("read_count") or 0, 

309 "url": page_url(document), 

310 "full_text_url": pdf_url(document), 

311 } 

312 

313 @_tool 

314 def resolve( 

315 self, 

316 kind: Annotated[ 

317 Literal["journal", "institution", "concept", "planetary_feature"], 

318 Field(description="What the name is of. `concept` is a Unified Astronomy Thesaurus concept."), 

319 ], 

320 name: Annotated[str, Field(description="The name, or part of it; for a journal, its abbreviation works too.")], 

321 limit: Annotated[int, Field(ge=1, le=50, description="How many matches to return.")] = 10, 

322 ) -> dict[str, Any]: 

323 """Find the identifier SciX uses for a journal, an institution, a UAT concept or a planetary feature. 

324 

325 Nothing is sent to SciX: the names are looked up in reference data held 

326 locally. Each match says how to search for it (`search_with`), which 

327 can be put in a `search` query as it is. 

328 """ 

329 text = name.strip() 

330 if not text: 

331 raise ValueError("The name is empty.") 

332 matches: list[dict[str, Any]] 

333 if kind == "journal": 

334 matches = self._journals(text, limit) 

335 elif kind == "institution": 

336 matches = self._institutions(text, limit) 

337 elif kind == "concept": 

338 matches = self._concepts(text, limit) 

339 else: 

340 matches = self._features(text, limit) 

341 return {"kind": kind, "name": text, "matches": matches} 

342 

343 def _journals(self, text: str, limit: int) -> list[dict[str, Any]]: 

344 found: dict[str, str] = {} 

345 named = _journals().named(text) 

346 if named is not None: 

347 found[named[0]] = named[1] 

348 titled = Journal.select().where(Journal.title.contains(text) | Journal.abbreviation.startswith(text)).all() 

349 for journal in _ranked(text, titled, lambda journal: [journal.title or "", journal.abbreviation or ""]): 

350 if journal.abbreviation: 350 ↛ 349line 350 didn't jump to line 349 because the condition on line 350 was always true

351 found.setdefault(journal.abbreviation, journal.title or "") 

352 return [ 

353 {"abbreviation": abbreviation, "title": title, "search_with": f'journal:"{abbreviation}"'} 

354 for abbreviation, title in list(found.items())[:limit] 

355 ] 

356 

357 def _institutions(self, text: str, limit: int) -> list[dict[str, Any]]: 

358 condition = Affiliation.canonical_name.contains(text) | Affiliation.abbreviation.contains(text) 

359 rows = Affiliation.select().where(condition | (Affiliation.id == text)).all() 

360 ranked = _ranked(text, rows, lambda row: [row.abbreviation or "", row.canonical_name or "", row.id or ""]) 

361 matches = [] 

362 for row in ranked[:limit]: 

363 parent = row.parent 

364 match = { 

365 "id": row.id, 

366 "abbreviation": row.abbreviation, 

367 "name": row.canonical_name, 

368 "country": row.country, 

369 "part_of": parent.abbreviation if parent is not None else None, 

370 "search_with": f"aff_id:{row.id}", 

371 } 

372 if parent is None: 

373 # inst: also finds the institution's departments, which aff_id: does not. A department's 

374 # abbreviation ("Sch Phy") is shared with other institutions', so only its id is given. 

375 match["search_with"] = f'inst:"{row.abbreviation}"' 

376 match["search_without_its_parts_with"] = f"aff_id:{row.id}" 

377 matches.append(match) 

378 return matches 

379 

380 def _concepts(self, text: str, limit: int) -> list[dict[str, Any]]: 

381 thesaurus = _thesaurus() 

382 if thesaurus is None: 

383 UATConcept.select().first() # raises DataNotAvailable, which says what to run 

384 rows = UATConcept.select().where((UATConcept.name == text) | (UATConcept.alt_names == text)).all() 

385 exact = thesaurus.named(text) if thesaurus is not None else None 

386 if exact is not None and exact not in rows: 

387 rows.insert(0, exact) 

388 ranked = _ranked(text, rows, lambda row: [row.name or "", *(row.alt_names or ())]) 

389 if exact is not None: 389 ↛ 391line 389 didn't jump to line 391 because the condition on line 389 was always true

390 ranked = [exact, *(row for row in ranked if row != exact)] 

391 return [ 

392 { 

393 "id": row.id, 

394 "name": row.name, 

395 "other_names": list(row.alt_names or ()), 

396 "broader": [parent.name for parent in row.parents], 

397 "narrower": [child.name for child in row.children.limit(15)], 

398 "search_with": f"uat:{row.id}", 

399 } 

400 for row in ranked[:limit] 

401 if not row.deprecated 

402 ] 

403 

404 def _features(self, text: str, limit: int) -> list[dict[str, Any]]: 

405 rows = PlanetaryFeature.select().where(PlanetaryFeature.name == text).all() 

406 ranked = _ranked(text, rows, lambda row: [row.name or ""]) 

407 return [ 

408 { 

409 "id": row.id, 

410 "name": row.name, 

411 "on": row.target, 

412 "type": row.feature_type, 

413 "search_with": f"planetary_feature_id:{row.id}", 

414 } 

415 for row in ranked[:limit] 

416 ] 

417 

418 # Services. 

419 

420 @_tool 

421 def export( 

422 self, 

423 bibcodes: Annotated[list[str], Field(min_length=1, max_length=MAX_DOCUMENTS, description=_BIBCODES)], 

424 format: Annotated[ExportFormat, Field(description="The format; bibtexabs is BibTeX with abstracts.")] = "bibtex", 

425 ) -> str: 

426 """Export documents as BibTeX, AASTeX, RIS, EndNote or another reference format.""" 

427 text: str = getattr(export_service, format)(self._bibcodes(bibcodes, None, 0), client=self.client) 

428 return text 

429 

430 @_tool 

431 def metrics( 

432 self, 

433 bibcodes: Annotated[ 

434 list[str] | None, Field(min_length=1, max_length=MAX_DOCUMENTS, description=_BIBCODES) 

435 ] = None, 

436 query: Annotated[str | None, Field(description=_FROM_QUERY)] = None, 

437 limit: Annotated[ 

438 int, Field(ge=1, le=MAX_DOCUMENTS, description="With `query`: how many of its results to use.") 

439 ] = MAX_DOCUMENTS, 

440 per_year: Annotated[ 

441 bool, Field(description="Also give the counts and indicators for each year (a long answer).") 

442 ] = False, 

443 ) -> dict[str, Any]: 

444 """Citation and usage statistics for a set of documents taken together. 

445 

446 Gives the number of papers, reads and downloads (`basic`), citations 

447 (`citations`), and indicators such as the h-index (`indicators`: h, g, 

448 i10, i100, m, tori, riq, read10); `refereed` holds the same for the 

449 refereed documents alone. Give bibcodes, or a query such as 

450 orcid:0000-0002-1825-0097 for everything by one author. 

451 """ 

452 chosen = self._bibcodes(bibcodes, query, limit) 

453 types = ["basic", "citations", "indicators"] + (["histograms", "timeseries"] if per_year else []) 

454 data = metrics_service(chosen, types=types, client=self.client) 

455 sections = {"basic": "basic stats", "citations": "citation stats", "indicators": "indicators"} 

456 

457 def section(key: str) -> dict[str, Any]: 

458 value = data.get(key) 

459 # The list of self-citations can run to thousands of bibcodes; its count is kept. 

460 return {name: each for name, each in value.items() if name != "self-citations"} if isinstance(value, dict) else {} 

461 

462 result: dict[str, Any] = {"documents": len(chosen), "skipped": data.get("skipped bibcodes") or []} 

463 result.update({name: section(key) for name, key in sections.items()}) 

464 result["refereed"] = {name: section(f"{key} refereed") for name, key in sections.items()} 

465 if per_year: 

466 result["per_year"] = {"histograms": data.get("histograms"), "time_series": data.get("time series")} 

467 return result 

468 

469 # Libraries. 

470 

471 def _find_library(self, library: str) -> Library: 

472 """The library with this id or name: one of the user's, or a public one by id.""" 

473 wanted = library.strip() 

474 if not wanted: 

475 raise ValueError("The library is empty: give its id or its name.") 

476 mine = Library.select().using(self.client).all() 

477 tests: tuple[Callable[[Library], bool], ...] = ( 

478 lambda each: each.id == wanted, 

479 lambda each: each.name == wanted, 

480 lambda each: (each.name or "").lower() == wanted.lower(), 

481 ) 

482 for test in tests: 

483 found = [each for each in mine if test(each)] 

484 if len(found) > 1: 

485 ids = ", ".join(str(each.id) for each in found) 

486 raise ToolError(f"{len(found)} libraries are named {wanted!r}; give the id of one of them: {ids}.") 

487 if found: 

488 found[0].client = self.client 

489 return found[0] 

490 if re.fullmatch(r"[A-Za-z0-9_-]{16,}", wanted): 

491 # Not one of the user's: it may be someone else's public library. 

492 try: 

493 other = Library.select().where(Library.id == wanted).using(self.client).first() 

494 except APIError: 

495 other = None 

496 if other is not None: 496 ↛ 497line 496 didn't jump to line 497 because the condition on line 496 was never true

497 other.client = self.client 

498 return other 

499 names = ", ".join(repr(each.name) for each in mine) or "none" 

500 raise ToolError(f"No library has the id or name {wanted!r}. The user's libraries: {names}.") 

501 

502 @_tool 

503 def list_libraries(self) -> dict[str, Any]: 

504 """List the user's SciX libraries: their ids, names, descriptions and sizes.""" 

505 libraries = Library.select().using(self.client).all() 

506 return {"libraries": [_library(library) for library in libraries]} 

507 

508 @_tool 

509 def get_library( 

510 self, 

511 library: Annotated[str, Field(description=_LIBRARY)], 

512 limit: Annotated[int, Field(ge=1, le=100, description="How many of its documents to return.")] = 25, 

513 offset: Annotated[int, Field(ge=0, description="How many documents to skip, to see the next page.")] = 0, 

514 sort: Annotated[SortName | None, Field(description="The order of the documents (default: date, newest first).")] = None, 

515 ) -> dict[str, Any]: 

516 """Get a SciX library: what it is, and the documents in it.""" 

517 found = self._find_library(library) 

518 name = found.name or str(found.id) 

519 contents = Interpretation(name, (Reading("library", name, name, Document.in_(found)),)) 

520 documents, total = self.session.fetch(contents, sort or "date", limit=limit, offset=offset) 

521 return { 

522 "library": _library(found), 

523 "total": total, 

524 "offset": offset, 

525 "documents": [_brief(document) for document in documents], 

526 } 

527 

528 @_tool 

529 def create_library( 

530 self, 

531 name: Annotated[str, Field(min_length=1, description="The name, which no other library of the user may have.")], 

532 description: Annotated[str | None, Field(description="What the library is for.")] = None, 

533 public: Annotated[bool, Field(description="Whether anyone may read it.")] = False, 

534 bibcodes: Annotated[list[str] | None, Field(max_length=MAX_DOCUMENTS, description=_BIBCODES)] = None, 

535 query: Annotated[str | None, Field(description=_FROM_QUERY)] = None, 

536 limit: Annotated[int, Field(ge=1, le=MAX_DOCUMENTS, description="With `query`: how many of its results to add.")] = 25, 

537 ) -> dict[str, Any]: 

538 """Create a library on the user's SciX account, empty or holding the documents given.""" 

539 documents = [] if bibcodes is None and query is None else self._bibcodes(bibcodes, query, limit) 

540 created = Library.create(name, description, public, documents, client=self.client) 

541 return {"created": _library(created)} 

542 

543 @_tool 

544 def edit_library( 

545 self, 

546 library: Annotated[str, Field(description=_LIBRARY)], 

547 name: Annotated[str | None, Field(description="A new name.")] = None, 

548 description: Annotated[str | None, Field(description="A new description.")] = None, 

549 public: Annotated[bool | None, Field(description="Whether anyone may read it.")] = None, 

550 ) -> dict[str, Any]: 

551 """Change a library's name, description or whether it is public. Only what is given changes.""" 

552 found = self._find_library(library) 

553 found.update(name=name, description=description, public=public) 

554 return {"library": _library(found)} 

555 

556 @_tool 

557 def add_to_library( 

558 self, 

559 library: Annotated[str, Field(description=_LIBRARY)], 

560 bibcodes: Annotated[list[str] | None, Field(max_length=MAX_DOCUMENTS, description=_BIBCODES)] = None, 

561 query: Annotated[str | None, Field(description=_FROM_QUERY)] = None, 

562 limit: Annotated[int, Field(ge=1, le=MAX_DOCUMENTS, description="With `query`: how many of its results to add.")] = 25, 

563 ) -> dict[str, Any]: 

564 """Add documents to a library: bibcodes, or the results of a search.""" 

565 found = self._find_library(library) 

566 chosen = self._bibcodes(bibcodes, query, limit) 

567 added = found.add(chosen) 

568 return {"added": added, "already_there": len(chosen) - added, "library": _library(found)} 

569 

570 @_tool 

571 def remove_from_library( 

572 self, 

573 library: Annotated[str, Field(description=_LIBRARY)], 

574 bibcodes: Annotated[list[str], Field(min_length=1, max_length=MAX_DOCUMENTS, description=_BIBCODES)], 

575 ) -> dict[str, Any]: 

576 """Remove documents from a library. The documents themselves are not affected.""" 

577 found = self._find_library(library) 

578 removed = found.remove(self._bibcodes(bibcodes, None, 0)) 

579 return {"removed": removed, "library": _library(found)} 

580 

581 @_tool 

582 def combine_libraries( 

583 self, 

584 operation: Annotated[ 

585 Literal["union", "intersection", "difference"], 

586 Field( 

587 description="union: documents in any of them; intersection: documents in all of them; " 

588 "difference: documents in `library` but in none of `others`." 

589 ), 

590 ], 

591 library: Annotated[str, Field(description=_LIBRARY)], 

592 others: Annotated[list[str], Field(min_length=1, description="The other libraries: ids or exact names.")], 

593 name: Annotated[str | None, Field(description="The name of the new library (SciX chooses one if not given).")] = None, 

594 description: Annotated[str | None, Field(description="What the new library is for.")] = None, 

595 public: Annotated[bool, Field(description="Whether anyone may read the new library.")] = False, 

596 ) -> dict[str, Any]: 

597 """Make a new library from two or more: their union, intersection or difference. The originals are kept.""" 

598 first = self._find_library(library) 

599 rest = [self._find_library(other) for other in others] 

600 combine = getattr(first, operation) 

601 created: Library = combine(*rest, name=name, description=description, public=public, client=self.client) 

602 return {"created": _library(created)} 

603 

604 @_tool 

605 def delete_library( 

606 self, 

607 library: Annotated[str, Field(description=_LIBRARY)], 

608 ) -> dict[str, Any]: 

609 """Delete a library from the user's SciX account, for good. This cannot be undone.""" 

610 found = self._find_library(library) 

611 deleted = _library(found) 

612 found.delete() 

613 return {"deleted": deleted} 

614 

615 

616def build(client: Client | None = None, *, read_only: bool = False) -> MCPServer: 

617 """The MCP server with its tools registered. 

618 

619 :param client: the client to send requests with (default: the default client). 

620 :param read_only: leave out the tools that create, change or delete libraries. 

621 """ 

622 tools = Tools(client) 

623 server = MCPServer( 

624 "scixplorer", 

625 title="SciX", 

626 instructions=INSTRUCTIONS, 

627 version=__version__, 

628 website_url="https://andycasey.github.io/scixplorer/", 

629 log_level="WARNING", 

630 ) 

631 local = ToolAnnotations(read_only_hint=True, open_world_hint=False) 

632 reads = ToolAnnotations(read_only_hint=True, open_world_hint=True) 

633 adds = ToolAnnotations(read_only_hint=False, destructive_hint=False, idempotent_hint=False, open_world_hint=True) 

634 changes = ToolAnnotations(read_only_hint=False, destructive_hint=True, idempotent_hint=True, open_world_hint=True) 

635 server.add_tool(tools.search, title="Search SciX", annotations=reads) 

636 server.add_tool(tools.explain_search, title="Explain a search", annotations=local) 

637 server.add_tool(tools.get_document, title="Get a document", annotations=reads) 

638 server.add_tool(tools.resolve, title="Resolve a name", annotations=local) 

639 server.add_tool(tools.export, title="Export references", annotations=reads, structured_output=False) 

640 server.add_tool(tools.metrics, title="Citation metrics", annotations=reads) 

641 server.add_tool(tools.list_libraries, title="List libraries", annotations=reads) 

642 server.add_tool(tools.get_library, title="Get a library", annotations=reads) 

643 if not read_only: 

644 server.add_tool(tools.create_library, title="Create a library", annotations=adds) 

645 server.add_tool(tools.add_to_library, title="Add to a library", annotations=adds) 

646 server.add_tool(tools.combine_libraries, title="Combine libraries", annotations=adds) 

647 server.add_tool(tools.edit_library, title="Edit a library", annotations=changes) 

648 server.add_tool(tools.remove_from_library, title="Remove from a library", annotations=changes) 

649 server.add_tool(tools.delete_library, title="Delete a library", annotations=changes) 

650 return server 

651 

652 

653def serve(client: Client | None = None, *, read_only: bool = False) -> None: 

654 """Run the server on standard input and output until the client disconnects.""" 

655 build(client, read_only=read_only).run("stdio")