CifQL 0.2.0__tar.gz → 0.3.0__tar.gz

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.
Files changed (55) hide show
  1. {cifql-0.2.0 → cifql-0.3.0}/CifQL.egg-info/PKG-INFO +1 -1
  2. {cifql-0.2.0 → cifql-0.3.0}/CifQL.egg-info/SOURCES.txt +2 -0
  3. {cifql-0.2.0 → cifql-0.3.0}/PKG-INFO +1 -1
  4. {cifql-0.2.0 → cifql-0.3.0}/cifql/__init__.py +1 -1
  5. {cifql-0.2.0 → cifql-0.3.0}/cifql/_argparse.py +18 -14
  6. {cifql-0.2.0 → cifql-0.3.0}/cifql/_config.py +12 -8
  7. {cifql-0.2.0 → cifql-0.3.0}/cifql/_logging.py +44 -6
  8. {cifql-0.2.0 → cifql-0.3.0}/cifql/loader.py +22 -1
  9. {cifql-0.2.0 → cifql-0.3.0}/cifql/mcp_server/query.py +74 -0
  10. {cifql-0.2.0 → cifql-0.3.0}/cifql/mcp_server/server.py +131 -6
  11. cifql-0.3.0/cifql/mcp_server/tool_log.py +126 -0
  12. {cifql-0.2.0 → cifql-0.3.0}/tests/test_argparse.py +25 -0
  13. {cifql-0.2.0 → cifql-0.3.0}/tests/test_cif2db.py +13 -0
  14. {cifql-0.2.0 → cifql-0.3.0}/tests/test_config.py +22 -7
  15. {cifql-0.2.0 → cifql-0.3.0}/tests/test_loader.py +58 -0
  16. {cifql-0.2.0 → cifql-0.3.0}/tests/test_logging.py +91 -0
  17. {cifql-0.2.0 → cifql-0.3.0}/tests/test_mcp_query.py +88 -0
  18. {cifql-0.2.0 → cifql-0.3.0}/tests/test_mcp_server.py +277 -17
  19. cifql-0.3.0/tests/test_mcp_tool_log.py +269 -0
  20. {cifql-0.2.0 → cifql-0.3.0}/tests/test_orm.py +13 -4
  21. {cifql-0.2.0 → cifql-0.3.0}/CifQL.egg-info/dependency_links.txt +0 -0
  22. {cifql-0.2.0 → cifql-0.3.0}/CifQL.egg-info/entry_points.txt +0 -0
  23. {cifql-0.2.0 → cifql-0.3.0}/CifQL.egg-info/requires.txt +0 -0
  24. {cifql-0.2.0 → cifql-0.3.0}/CifQL.egg-info/top_level.txt +0 -0
  25. {cifql-0.2.0 → cifql-0.3.0}/LICENSE +0 -0
  26. {cifql-0.2.0 → cifql-0.3.0}/README.md +0 -0
  27. {cifql-0.2.0 → cifql-0.3.0}/cifql/__main__.py +0 -0
  28. {cifql-0.2.0 → cifql-0.3.0}/cifql/_checks.py +0 -0
  29. {cifql-0.2.0 → cifql-0.3.0}/cifql/_cli.py +0 -0
  30. {cifql-0.2.0 → cifql-0.3.0}/cifql/_errors.py +0 -0
  31. {cifql-0.2.0 → cifql-0.3.0}/cifql/_orm.py +0 -0
  32. {cifql-0.2.0 → cifql-0.3.0}/cifql/_utils.py +0 -0
  33. {cifql-0.2.0 → cifql-0.3.0}/cifql/cif2db.py +0 -0
  34. {cifql-0.2.0 → cifql-0.3.0}/cifql/completion.py +0 -0
  35. {cifql-0.2.0 → cifql-0.3.0}/cifql/dic2json.py +0 -0
  36. {cifql-0.2.0 → cifql-0.3.0}/cifql/dic2orm.py +0 -0
  37. {cifql-0.2.0 → cifql-0.3.0}/cifql/dic_usage.py +0 -0
  38. {cifql-0.2.0 → cifql-0.3.0}/cifql/dics/__init__.py +0 -0
  39. {cifql-0.2.0 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/__init__.py +0 -0
  40. {cifql-0.2.0 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/v5_417/__init__.py +0 -0
  41. {cifql-0.2.0 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/v5_417/dic_descriptions.py +0 -0
  42. {cifql-0.2.0 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/v5_417/ingest.py +0 -0
  43. {cifql-0.2.0 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/v5_417/models.py +0 -0
  44. {cifql-0.2.0 → cifql-0.3.0}/cifql/mcp_server/__init__.py +0 -0
  45. {cifql-0.2.0 → cifql-0.3.0}/cifql/text_index.py +0 -0
  46. {cifql-0.2.0 → cifql-0.3.0}/pyproject.toml +0 -0
  47. {cifql-0.2.0 → cifql-0.3.0}/setup.cfg +0 -0
  48. {cifql-0.2.0 → cifql-0.3.0}/tests/test_cli.py +0 -0
  49. {cifql-0.2.0 → cifql-0.3.0}/tests/test_completion.py +0 -0
  50. {cifql-0.2.0 → cifql-0.3.0}/tests/test_dic2json.py +0 -0
  51. {cifql-0.2.0 → cifql-0.3.0}/tests/test_dic2orm.py +0 -0
  52. {cifql-0.2.0 → cifql-0.3.0}/tests/test_dic_usage.py +0 -0
  53. {cifql-0.2.0 → cifql-0.3.0}/tests/test_errors.py +0 -0
  54. {cifql-0.2.0 → cifql-0.3.0}/tests/test_text_index.py +0 -0
  55. {cifql-0.2.0 → cifql-0.3.0}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: CifQL
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: CifQL - mmCIF and ModelCIF files as one queryable relational database.
5
5
  Author-email: Bienchen <stefan.bienert@unibas.ch>
6
6
  License-Expression: MIT
@@ -33,6 +33,7 @@ cifql/dics/mmcif_pdbx/v5_417/models.py
33
33
  cifql/mcp_server/__init__.py
34
34
  cifql/mcp_server/query.py
35
35
  cifql/mcp_server/server.py
36
+ cifql/mcp_server/tool_log.py
36
37
  tests/test_argparse.py
37
38
  tests/test_cif2db.py
38
39
  tests/test_cli.py
@@ -46,6 +47,7 @@ tests/test_loader.py
46
47
  tests/test_logging.py
47
48
  tests/test_mcp_query.py
48
49
  tests/test_mcp_server.py
50
+ tests/test_mcp_tool_log.py
49
51
  tests/test_orm.py
50
52
  tests/test_text_index.py
51
53
  tests/test_utils.py
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: CifQL
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: CifQL - mmCIF and ModelCIF files as one queryable relational database.
5
5
  Author-email: Bienchen <stefan.bienert@unibas.ch>
6
6
  License-Expression: MIT
@@ -21,4 +21,4 @@
21
21
  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
22
  # SOFTWARE.
23
23
 
24
- __version__ = "0.2.0"
24
+ __version__ = "0.3.0"
@@ -86,6 +86,17 @@ class _CheckedMutuallyExclusiveGroup(
86
86
  """Mutually exclusive group whose arguments carry checks."""
87
87
 
88
88
 
89
+ def _permitted(fst, user, group, other):
90
+ """Whether the mode in `fst` grants the bit for whom the process is: its
91
+ owner, a member of its group, anyone else."""
92
+ if os.geteuid() == fst.st_uid:
93
+ return bool(fst.st_mode & user)
94
+ if fst.st_gid == os.getegid() or fst.st_gid in os.getgroups():
95
+ return bool(fst.st_mode & group)
96
+
97
+ return bool(fst.st_mode & other)
98
+
99
+
89
100
  def check_output_dir(directory, parser):
90
101
  """Check that a directory exists and is writable.
91
102
  If directory is `None`, function just returns."""
@@ -137,6 +148,12 @@ def check_output_file(file_path, parser):
137
148
  parser.error(
138
149
  f"Path '{file_path}' is pointing to an existing directory", 105
139
150
  )
151
+ try:
152
+ fst = file_path.stat()
153
+ except FileNotFoundError:
154
+ return
155
+ if not _permitted(fst, stat.S_IWUSR, stat.S_IWGRP, stat.S_IWOTH):
156
+ parser.error(f"Output file '{file_path}' is not writable", 115)
140
157
 
141
158
 
142
159
  def check_input_dir(directory, parser):
@@ -192,20 +209,7 @@ def check_input_file(file_path, parser):
192
209
  if stat.S_ISDIR(fst.st_mode):
193
210
  parser.error(f"Input file '{file_path}' is a directory", 113)
194
211
 
195
- mode = fst.st_mode
196
- uid, gid = fst.st_uid, fst.st_gid
197
- euid, egid = os.geteuid(), os.getegid()
198
- groups = os.getgroups()
199
-
200
- # check accessibility
201
- if euid == uid:
202
- can_read = bool(mode & stat.S_IRUSR)
203
- elif gid == egid or gid in groups:
204
- can_read = bool(mode & stat.S_IRGRP)
205
- else:
206
- can_read = bool(mode & stat.S_IROTH)
207
-
208
- if not can_read:
212
+ if not _permitted(fst, stat.S_IRUSR, stat.S_IRGRP, stat.S_IROTH):
209
213
  parser.error(f"Input file '{file_path}' is not readable", 114)
210
214
 
211
215
 
@@ -32,8 +32,8 @@ logger = logging.getLogger(__name__)
32
32
 
33
33
 
34
34
  def _read_yaml(path, source):
35
- """The mapping in the YAML file `path`, None for an empty file. `source`
36
- says where the path came from."""
35
+ """The mapping in the YAML file `path`. `source` says where the path came
36
+ from."""
37
37
  try:
38
38
  with open(path, encoding="utf8") as yfh:
39
39
  config = yaml.safe_load(yfh)
@@ -43,12 +43,19 @@ def _read_yaml(path, source):
43
43
  raise ConfigError(
44
44
  f"Configuration file '{path}' ({source}) can not be used: {reason}"
45
45
  ) from exc
46
- if config is not None and not isinstance(config, dict):
46
+ # An empty file is never what someone meant, the next source would be
47
+ # used without them knowing.
48
+ if config is None:
49
+ raise ConfigError(
50
+ f"Configuration file '{path}' ({source}) can not be used: it is "
51
+ + "empty"
52
+ )
53
+ if not isinstance(config, dict):
47
54
  raise ConfigError(
48
55
  f"Configuration file '{path}' ({source}) can not be used: not a "
49
56
  + "mapping of settings"
50
57
  )
51
- databases = (config or {}).get("DATABASES", {})
58
+ databases = config.get("DATABASES", {})
52
59
  if not isinstance(databases, dict) or not all(
53
60
  isinstance(settings, dict) for settings in databases.values()
54
61
  ):
@@ -86,13 +93,10 @@ def get_config(path_to_yaml=None):
86
93
  (os.environ.get("CIFQL_CONFIG_YAML", None), "$CIFQL_CONFIG_YAML"),
87
94
  (conf_file, "default path"),
88
95
  ]
89
- config = None
90
96
  for src in sources:
91
97
  if src[0] is not None:
92
- config = _read_yaml(*src)
93
- if config is not None:
98
+ defaults.update(_read_yaml(*src))
94
99
  logger.debug("Reading config from %s (%s)", src[1], src[0])
95
- defaults.update(config)
96
100
  return defaults
97
101
 
98
102
  logger.warning("No config found/ specified, running with defaults.")
@@ -22,6 +22,7 @@
22
22
  # SOFTWARE.
23
23
 
24
24
  import logging
25
+ import logging.handlers
25
26
 
26
27
 
27
28
  def init_logger(loglevel):
@@ -38,12 +39,49 @@ def init_logger(loglevel):
38
39
 
39
40
  handler = logging.StreamHandler()
40
41
  handler.set_name("cifql")
41
- handler.setFormatter(
42
- logging.Formatter(
43
- fmt="%(asctime)s - %(levelname)s | %(message)s",
44
- datefmt="%m/%d/%Y %H:%M:%S",
45
- )
46
- )
42
+ handler.setFormatter(_formatter())
47
43
  logger.addHandler(handler)
48
44
 
49
45
  return logger
46
+
47
+
48
+ def _formatter():
49
+ """CifQL's log format, on the terminal and in a file."""
50
+ return logging.Formatter(
51
+ fmt="%(asctime)s - %(levelname)s | %(message)s",
52
+ datefmt="%m/%d/%Y %H:%M:%S",
53
+ )
54
+
55
+
56
+ def _drop(logger, name):
57
+ """Remove and close `logger`'s handler `name`, if there is one."""
58
+ for handler in logger.handlers[:]:
59
+ if handler.name == name:
60
+ logger.removeHandler(handler)
61
+ handler.close()
62
+
63
+
64
+ def log_to_file(path, max_bytes, backups):
65
+ """Log into the file `path` instead of the terminal, rotated at
66
+ `max_bytes`, keeping `backups` old files. Errors also reach the terminal
67
+ until end_startup()."""
68
+ logger = logging.getLogger()
69
+ # Opened first: a file that can not be, leaves the terminal as it was.
70
+ handler = logging.handlers.RotatingFileHandler(
71
+ path, maxBytes=max_bytes, backupCount=backups, encoding="utf8"
72
+ )
73
+ _drop(logger, "cifql")
74
+ # init_logger() finds it by name and leaves it.
75
+ handler.set_name("cifql")
76
+ handler.setFormatter(_formatter())
77
+ logger.addHandler(handler)
78
+ startup = logging.StreamHandler()
79
+ startup.set_name("cifql-startup")
80
+ startup.setLevel(logging.ERROR)
81
+ startup.setFormatter(_formatter())
82
+ logger.addHandler(startup)
83
+
84
+
85
+ def end_startup():
86
+ """The server is up: errors go to the log file alone."""
87
+ _drop(logging.getLogger(), "cifql-startup")
@@ -72,6 +72,7 @@ from pathlib import Path
72
72
  import importlib.machinery
73
73
  import importlib.util
74
74
  import os
75
+ import traceback
75
76
 
76
77
  from ._errors import LoaderFileError
77
78
 
@@ -102,6 +103,19 @@ class Loader:
102
103
  it as it is."""
103
104
 
104
105
 
106
+ def _traceback_in(exc, plugin):
107
+ """The traceback of `exc` from the first line of the file `plugin` on,
108
+ Python's import machinery before it says nothing to its author."""
109
+ frames = exc.__traceback__
110
+ while (
111
+ frames is not None
112
+ and frames.tb_frame.f_code.co_filename != os.fspath(plugin)
113
+ ):
114
+ frames = frames.tb_next
115
+
116
+ return "".join(traceback.format_exception(type(exc), exc, frames)).rstrip()
117
+
118
+
105
119
  def load_loader(plugin):
106
120
  """The one Loader subclass defined in the Python file `plugin`."""
107
121
  name = f"cifql_loader_{Path(plugin).stem}"
@@ -110,7 +124,14 @@ def load_loader(plugin):
110
124
  name, importlib.machinery.SourceFileLoader(name, os.fspath(plugin))
111
125
  )
112
126
  module = importlib.util.module_from_spec(spec)
113
- spec.loader.exec_module(module)
127
+ try:
128
+ spec.loader.exec_module(module)
129
+ # Whatever the loader's own code raises, a syntax error included.
130
+ except Exception as exc: # pylint: disable=broad-exception-caught
131
+ raise LoaderFileError(
132
+ f"'{plugin}' can not be loaded: {type(exc).__name__}: {exc}\n"
133
+ + _traceback_in(exc, plugin)
134
+ ) from exc
114
135
  found = sorted(
115
136
  (
116
137
  obj
@@ -536,6 +536,50 @@ class Explorer: # pylint: disable=too-many-instance-attributes
536
536
 
537
537
  return None
538
538
 
539
+ @staticmethod
540
+ def _link_spelt(model, part):
541
+ """The link of `model` that `part` names when underscores are left
542
+ out: a category as the dictionary writes it, 'entity_src_gen', is
543
+ the link 'entitysrcgen'. Items are not compared this way."""
544
+ wanted = part.replace("_", "")
545
+ for fld in model._meta.get_fields():
546
+ if fld.is_relation and fld.name.replace("_", "") == wanted:
547
+ return fld
548
+
549
+ return None
550
+
551
+ def _leads_on(self, model, fld, part):
552
+ """Whether the link `fld` of `model` may show the way to `part`: to
553
+ another category, and nothing hidden on either side."""
554
+ target = fld.related_model
555
+ return (
556
+ fld.is_relation
557
+ and target is not model
558
+ and hasattr(target, "cif_name")
559
+ and not (model is self.block and fld.name in INTERNAL)
560
+ and not (target is self.block and part in INTERNAL)
561
+ )
562
+
563
+ def _ways_to(self, model, part):
564
+ """The links of `model` to categories that have `part`, as (link,
565
+ category, the name there): a query that missed a category by one
566
+ link is told the way. Links back to `model` are no way further."""
567
+ ways = []
568
+ for fld in model._meta.get_fields():
569
+ if not self._leads_on(model, fld, part):
570
+ continue
571
+ target = fld.related_model
572
+ try:
573
+ found = target._meta.get_field(part)
574
+ except FieldDoesNotExist:
575
+ found = self._link_spelt(target, part)
576
+ if found is not None and not (
577
+ found.is_relation and found.related_model is model
578
+ ):
579
+ ways.append((fld.name, target, found.name))
580
+
581
+ return ways
582
+
539
583
  def _resolve(self, model, lookup):
540
584
  """Check a Django lookup against the ORM. Returns the field it ends
541
585
  at and its comparison."""
@@ -563,6 +607,36 @@ class Explorer: # pylint: disable=too-many-instance-attributes
563
607
  except FieldDoesNotExist:
564
608
  if field is not None and last and part in field.get_lookups():
565
609
  return field, part
610
+ missed = f"'{lookup}': '{current.cif_name}' has no '{part}'"
611
+ spelt = self._link_spelt(current, part)
612
+ if spelt is not None:
613
+ raise QueryError(
614
+ f"{missed}, it is called '{spelt.name}' here: use '"
615
+ + "__".join(
616
+ parts[:pos] + [spelt.name] + parts[pos + 1 :]
617
+ )
618
+ + "'"
619
+ ) from None
620
+ ways = self._ways_to(current, part)
621
+ # A few ways are named, more get the list.
622
+ if 0 < len(ways) <= 3:
623
+ raise QueryError(
624
+ f"{missed}, it hangs off "
625
+ + " or ".join(
626
+ f"'{cat.cif_name}'"
627
+ + (f" as '{there}'" if there != part else "")
628
+ for _, cat, there in ways
629
+ )
630
+ + ": use "
631
+ + " or ".join(
632
+ "'"
633
+ + "__".join(
634
+ parts[:pos] + [link, there] + parts[pos + 1 :]
635
+ )
636
+ + "'"
637
+ for link, _, there in ways
638
+ )
639
+ ) from None
566
640
  names = sorted(
567
641
  fld.name
568
642
  for fld in current._meta.get_fields()
@@ -26,17 +26,23 @@ stdout instead."""
26
26
  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
27
  # SOFTWARE.
28
28
 
29
+ from pathlib import Path
30
+ from typing import Any, NamedTuple
31
+ import asyncio
29
32
  import logging
30
- from typing import Any
33
+ import os
31
34
 
32
35
  from django.core.exceptions import FieldError
33
36
  from django.db import DatabaseError
34
37
  from mcp.server.mcpserver import MCPServer
35
38
  from mcp.server.mcpserver.exceptions import ToolError
36
39
  from starlette.responses import JSONResponse
40
+ import uvicorn
37
41
 
38
- from .. import _argparse, _orm, _utils
42
+ from .. import _argparse, _logging, _orm, _utils
43
+ from .._errors import ConfigError
39
44
  from .query import Explorer, QueryError, load_descriptions, load_links
45
+ from .tool_log import ToolLog
40
46
 
41
47
  INSTRUCTIONS = (
42
48
  "Answers questions about the structures in a CifQL database, read from "
@@ -155,12 +161,35 @@ def _answer(func, *args, **kwargs):
155
161
  raise ToolError(f"{type(exc).__name__}: {exc}") from exc
156
162
 
157
163
 
158
- def build_server(explorer):
159
- """An MCPServer with the four tools on `explorer`."""
164
+ class _UpServer(uvicorn.Server):
165
+ """uvicorn's server, the server is up once it has bound its port."""
166
+
167
+ async def startup(self, sockets=None):
168
+ await super().startup(sockets)
169
+ _logging.end_startup()
170
+
171
+
172
+ def _serve_http(mcp_server, host, port): # pragma: no cover
173
+ """Serve HTTP like MCPServer.run(), but with uvicorn's lines passed on to
174
+ CifQL's log. Runs until stopped, tried by hand."""
175
+ config = uvicorn.Config(
176
+ mcp_server.streamable_http_app(host=host),
177
+ host=host,
178
+ port=port,
179
+ log_level="info",
180
+ log_config=None,
181
+ )
182
+ asyncio.run(_UpServer(config).serve())
183
+
184
+
185
+ def build_server(explorer, tool_log=False):
186
+ """An MCPServer with the four tools on `explorer`; with `tool_log`,
187
+ every call the model makes is logged."""
160
188
  server = MCPServer(
161
189
  name="cifql",
162
190
  instructions=INSTRUCTIONS
163
191
  + (FULL_TEXT if explorer.full_text else FREE_TEXT),
192
+ extensions=[ToolLog()] if tool_log else None,
164
193
  )
165
194
 
166
195
  @server.custom_route("/health", methods=["GET"])
@@ -229,6 +258,71 @@ def build_server(explorer):
229
258
  return server
230
259
 
231
260
 
261
+ class LogSettings(NamedTuple):
262
+ """Where the server logs and when the file is rotated."""
263
+
264
+ path: Path
265
+ max_bytes: int
266
+ backups: int
267
+
268
+
269
+ def _from_config(mcp):
270
+ """The log settings in the configuration's 'MCP' section, checked."""
271
+ if not isinstance(mcp, dict):
272
+ raise ConfigError(
273
+ "The configuration's 'MCP' needs to map settings to values"
274
+ )
275
+ unknown = sorted(set(mcp) - {"LOG_BACKUPS", "LOG_FILE", "LOG_MAX_SIZE"})
276
+ if unknown:
277
+ raise ConfigError(
278
+ "Unknown settings in the configuration's 'MCP': "
279
+ + ", ".join(unknown)
280
+ )
281
+ path = mcp.get("LOG_FILE")
282
+ if path is not None:
283
+ if not isinstance(path, str):
284
+ raise ConfigError(
285
+ f"'MCP: LOG_FILE' needs to be a path, not {path!r}"
286
+ )
287
+ # Path("") is the current directory.
288
+ if not path:
289
+ raise ConfigError("'MCP: LOG_FILE' is empty")
290
+ path = Path(path)
291
+ if (
292
+ path.is_dir()
293
+ or not path.parent.is_dir()
294
+ or not os.access(path.parent, os.W_OK | os.X_OK)
295
+ or (path.exists() and not os.access(path, os.W_OK))
296
+ ):
297
+ raise ConfigError(f"'MCP: LOG_FILE' '{path}' can not be written")
298
+ for key in ("LOG_BACKUPS", "LOG_MAX_SIZE"):
299
+ value = mcp.get(key)
300
+ if value is not None and (
301
+ isinstance(value, bool) or not isinstance(value, int) or value < 1
302
+ ):
303
+ raise ConfigError(
304
+ f"'MCP: {key}' needs to be a whole number, 1 or more, not "
305
+ + repr(value)
306
+ )
307
+
308
+ return path, mcp.get("LOG_MAX_SIZE"), mcp.get("LOG_BACKUPS")
309
+
310
+
311
+ def log_settings(opts, config):
312
+ """The log file and its rotation, the command line before the
313
+ configuration's 'MCP' section; None without a log file."""
314
+ path, max_size, backups = _from_config(config.get("MCP", {}))
315
+ path = opts.log_file or path
316
+ if path is None:
317
+ return None
318
+
319
+ return LogSettings(
320
+ Path(path),
321
+ (opts.log_max_size or max_size or 10) * 1024 * 1024,
322
+ opts.log_backups or backups or 5,
323
+ )
324
+
325
+
232
326
  def add_parser(subparsers):
233
327
  """The command line of mcp, a sub-command of cifql."""
234
328
  parser = _argparse.add_command(subparsers, "mcp", __doc__, run)
@@ -241,6 +335,31 @@ def add_parser(subparsers):
241
335
  metavar="<HOST>",
242
336
  type=str,
243
337
  )
338
+ parser.add_argument(
339
+ "--log-backups",
340
+ default=None,
341
+ help="old log files kept, default 5, or 'LOG_BACKUPS' in the "
342
+ + "configuration's 'MCP'",
343
+ metavar="<N>",
344
+ type=_argparse.at_least_one,
345
+ )
346
+ parser.add_argument(
347
+ "--log-file",
348
+ default=None,
349
+ help="write the server's log there, with every tool call, instead "
350
+ + "of to the terminal; or 'LOG_FILE' in the configuration's 'MCP'",
351
+ metavar="<FILE>",
352
+ post_parse_check=_argparse.check_output_file,
353
+ type=Path,
354
+ )
355
+ parser.add_argument(
356
+ "--log-max-size",
357
+ default=None,
358
+ help="size in MB at which the log file is rotated, default 10, or "
359
+ + "'LOG_MAX_SIZE' in the configuration's 'MCP'",
360
+ metavar="<MB>",
361
+ type=_argparse.at_least_one,
362
+ )
244
363
  parser.add_argument(
245
364
  "--no-full-text",
246
365
  action="store_true",
@@ -268,6 +387,9 @@ def add_parser(subparsers):
268
387
  def run(opts):
269
388
  """Run as the mcp sub-command of cifql."""
270
389
  opts, config = _utils.script_preflight(opts)
390
+ settings = log_settings(opts, config)
391
+ if settings is not None:
392
+ _logging.log_to_file(*settings)
271
393
  models = _orm.setup_django(
272
394
  *_orm.orm_app(opts.dic), _orm.read_only(config["DATABASES"])
273
395
  )
@@ -289,11 +411,14 @@ def run(opts):
289
411
  else "off"
290
412
  ),
291
413
  )
292
- mcp_server = build_server(explorer)
414
+ mcp_server = build_server(explorer, tool_log=settings is not None)
293
415
  logging.getLogger("uvicorn.access").addFilter(QuietHealth())
294
416
  if opts.stdio:
417
+ _logging.end_startup()
295
418
  mcp_server.run(transport="stdio")
296
- else:
419
+ elif settings is None:
297
420
  mcp_server.run(
298
421
  transport="streamable-http", host=opts.host, port=opts.port
299
422
  )
423
+ else:
424
+ _serve_http(mcp_server, opts.host, opts.port)
@@ -0,0 +1,126 @@
1
+ """The tool log: one line per tool call the model makes, in the server's
2
+ log file. Who asked, which tool, the arguments as sent and what came back,
3
+ in short, so an answer can be checked by running its query again."""
4
+
5
+ # Copyright (c) 2026, SIB - Swiss Institute of Bioinformatics and
6
+ # Biozentrum - University of Basel
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+ #
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+ #
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ import asyncio
27
+ import json
28
+ import logging
29
+ import os
30
+
31
+ from mcp.server.extension import Extension
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ def summary(tool, answer):
37
+ """What came back from `tool`, in short."""
38
+ if tool == "search_dictionary":
39
+ names = [result["name"] for result in answer["results"]]
40
+ return "found " + (", ".join(names) or "nothing")
41
+ if tool == "describe_category":
42
+ return answer["category"] + (
43
+ "" if answer["in_database"] else " (not in the database)"
44
+ )
45
+ parts = [
46
+ f"{len(answer[key])} {key}"
47
+ for key in ("entries", "rows", "counts")
48
+ if key in answer
49
+ ]
50
+ if "columns" in answer:
51
+ parts.append("columns " + ", ".join(answer["columns"]))
52
+ parts += [
53
+ f"{key} {answer[key]}"
54
+ for key in ("total", "total_rows", "total_values")
55
+ if key in answer
56
+ ]
57
+ parts += [
58
+ f"{key} {answer[key]}"
59
+ for key in ("more", "more_rows", "more_values")
60
+ if answer.get(key)
61
+ ]
62
+
63
+ return ", ".join(parts)
64
+
65
+
66
+ class ToolLog(Extension):
67
+ """Logs every tool call, those refused before a tool runs too: the model
68
+ was told an error, it is part of what it did."""
69
+
70
+ identifier = "ch.unibas.cifql/tool-log"
71
+
72
+ def __init__(self):
73
+ # Calls without a session id share the server process.
74
+ self.process = format(os.getpid(), "x")
75
+
76
+ def conversation(self, ctx):
77
+ """Which conversation a call belongs to: the start of the session id
78
+ an HTTP client sends, else the server process."""
79
+ request = getattr(ctx, "request", None)
80
+ session_id = (
81
+ None if request is None else request.headers.get("mcp-session-id")
82
+ )
83
+
84
+ return session_id[:8] if session_id else self.process
85
+
86
+ def _log(self, params, ctx, rest):
87
+ """The call's line; the log's trouble must not become the model's."""
88
+ try:
89
+ logger.info(
90
+ "[%s] %s %s -> %s",
91
+ self.conversation(ctx),
92
+ params.name,
93
+ json.dumps(
94
+ params.arguments or {}, ensure_ascii=False, default=str
95
+ ),
96
+ rest,
97
+ )
98
+ except Exception: # pylint: disable=broad-exception-caught
99
+ pass
100
+
101
+ async def intercept_tool_call(self, params, ctx, call_next):
102
+ # A call that does not come back, the client cancelled it on its
103
+ # timeout say, is part of what the model did too.
104
+ try:
105
+ result = await call_next(ctx)
106
+ except asyncio.CancelledError:
107
+ self._log(params, ctx, "cancelled")
108
+ raise
109
+ except Exception as exc:
110
+ self._log(params, ctx, f"error: {type(exc).__name__}: {exc}")
111
+ raise
112
+ try:
113
+ text = result.content[0].text
114
+ if result.is_error:
115
+ # A validation error spans several lines.
116
+ rest = "error: " + " ".join(text.split())
117
+ else:
118
+ rest = summary(params.name, json.loads(text))
119
+ except Exception: # pylint: disable=broad-exception-caught
120
+ rest = "(no summary)"
121
+ self._log(params, ctx, rest)
122
+
123
+ return result
124
+
125
+
126
+ # LocalWords: MCP