CifQL 0.2.1__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.1 → cifql-0.3.0}/CifQL.egg-info/PKG-INFO +1 -1
  2. {cifql-0.2.1 → cifql-0.3.0}/CifQL.egg-info/SOURCES.txt +2 -0
  3. {cifql-0.2.1 → cifql-0.3.0}/PKG-INFO +1 -1
  4. {cifql-0.2.1 → cifql-0.3.0}/cifql/__init__.py +1 -1
  5. {cifql-0.2.1 → cifql-0.3.0}/cifql/_argparse.py +18 -14
  6. {cifql-0.2.1 → cifql-0.3.0}/cifql/_logging.py +44 -6
  7. {cifql-0.2.1 → cifql-0.3.0}/cifql/mcp_server/server.py +131 -6
  8. cifql-0.3.0/cifql/mcp_server/tool_log.py +126 -0
  9. {cifql-0.2.1 → cifql-0.3.0}/tests/test_argparse.py +25 -0
  10. {cifql-0.2.1 → cifql-0.3.0}/tests/test_logging.py +91 -0
  11. {cifql-0.2.1 → cifql-0.3.0}/tests/test_mcp_server.py +277 -17
  12. cifql-0.3.0/tests/test_mcp_tool_log.py +269 -0
  13. {cifql-0.2.1 → cifql-0.3.0}/CifQL.egg-info/dependency_links.txt +0 -0
  14. {cifql-0.2.1 → cifql-0.3.0}/CifQL.egg-info/entry_points.txt +0 -0
  15. {cifql-0.2.1 → cifql-0.3.0}/CifQL.egg-info/requires.txt +0 -0
  16. {cifql-0.2.1 → cifql-0.3.0}/CifQL.egg-info/top_level.txt +0 -0
  17. {cifql-0.2.1 → cifql-0.3.0}/LICENSE +0 -0
  18. {cifql-0.2.1 → cifql-0.3.0}/README.md +0 -0
  19. {cifql-0.2.1 → cifql-0.3.0}/cifql/__main__.py +0 -0
  20. {cifql-0.2.1 → cifql-0.3.0}/cifql/_checks.py +0 -0
  21. {cifql-0.2.1 → cifql-0.3.0}/cifql/_cli.py +0 -0
  22. {cifql-0.2.1 → cifql-0.3.0}/cifql/_config.py +0 -0
  23. {cifql-0.2.1 → cifql-0.3.0}/cifql/_errors.py +0 -0
  24. {cifql-0.2.1 → cifql-0.3.0}/cifql/_orm.py +0 -0
  25. {cifql-0.2.1 → cifql-0.3.0}/cifql/_utils.py +0 -0
  26. {cifql-0.2.1 → cifql-0.3.0}/cifql/cif2db.py +0 -0
  27. {cifql-0.2.1 → cifql-0.3.0}/cifql/completion.py +0 -0
  28. {cifql-0.2.1 → cifql-0.3.0}/cifql/dic2json.py +0 -0
  29. {cifql-0.2.1 → cifql-0.3.0}/cifql/dic2orm.py +0 -0
  30. {cifql-0.2.1 → cifql-0.3.0}/cifql/dic_usage.py +0 -0
  31. {cifql-0.2.1 → cifql-0.3.0}/cifql/dics/__init__.py +0 -0
  32. {cifql-0.2.1 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/__init__.py +0 -0
  33. {cifql-0.2.1 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/v5_417/__init__.py +0 -0
  34. {cifql-0.2.1 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/v5_417/dic_descriptions.py +0 -0
  35. {cifql-0.2.1 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/v5_417/ingest.py +0 -0
  36. {cifql-0.2.1 → cifql-0.3.0}/cifql/dics/mmcif_pdbx/v5_417/models.py +0 -0
  37. {cifql-0.2.1 → cifql-0.3.0}/cifql/loader.py +0 -0
  38. {cifql-0.2.1 → cifql-0.3.0}/cifql/mcp_server/__init__.py +0 -0
  39. {cifql-0.2.1 → cifql-0.3.0}/cifql/mcp_server/query.py +0 -0
  40. {cifql-0.2.1 → cifql-0.3.0}/cifql/text_index.py +0 -0
  41. {cifql-0.2.1 → cifql-0.3.0}/pyproject.toml +0 -0
  42. {cifql-0.2.1 → cifql-0.3.0}/setup.cfg +0 -0
  43. {cifql-0.2.1 → cifql-0.3.0}/tests/test_cif2db.py +0 -0
  44. {cifql-0.2.1 → cifql-0.3.0}/tests/test_cli.py +0 -0
  45. {cifql-0.2.1 → cifql-0.3.0}/tests/test_completion.py +0 -0
  46. {cifql-0.2.1 → cifql-0.3.0}/tests/test_config.py +0 -0
  47. {cifql-0.2.1 → cifql-0.3.0}/tests/test_dic2json.py +0 -0
  48. {cifql-0.2.1 → cifql-0.3.0}/tests/test_dic2orm.py +0 -0
  49. {cifql-0.2.1 → cifql-0.3.0}/tests/test_dic_usage.py +0 -0
  50. {cifql-0.2.1 → cifql-0.3.0}/tests/test_errors.py +0 -0
  51. {cifql-0.2.1 → cifql-0.3.0}/tests/test_loader.py +0 -0
  52. {cifql-0.2.1 → cifql-0.3.0}/tests/test_mcp_query.py +0 -0
  53. {cifql-0.2.1 → cifql-0.3.0}/tests/test_orm.py +0 -0
  54. {cifql-0.2.1 → cifql-0.3.0}/tests/test_text_index.py +0 -0
  55. {cifql-0.2.1 → 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.1
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.1
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.1"
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
 
@@ -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")
@@ -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
@@ -302,6 +302,31 @@ def test_check_output_file_is_a_directory(tmp_path):
302
302
  assert _code(_argparse.check_output_file, tmp_path) == 105
303
303
 
304
304
 
305
+ @pytest.mark.parametrize(
306
+ "owner,group,mode",
307
+ [(True, False, 0o400), (False, True, 0o040), (False, False, 0o004)],
308
+ ids=["owner", "group", "other"],
309
+ )
310
+ def test_check_output_file_not_writable(
311
+ tmp_path, monkeypatch, owner, group, mode
312
+ ):
313
+ """An existing output file not writable for whom the process is: 115."""
314
+ # Its directory open to all, the check gets to the file.
315
+ tmp_path.chmod(0o777)
316
+ a_file = tmp_path / "out.json"
317
+ a_file.write_text("content")
318
+ _as(monkeypatch, a_file, owner=owner, group=group)
319
+ a_file.chmod(mode)
320
+ assert _code(_argparse.check_output_file, a_file) == 115
321
+
322
+
323
+ def test_check_output_file_existing_and_writable(tmp_path):
324
+ """An existing file that may be written passes."""
325
+ a_file = tmp_path / "out.json"
326
+ a_file.write_text("content")
327
+ assert _argparse.check_output_file(a_file, _parser()) is None
328
+
329
+
305
330
  def test_check_output_file_ok(tmp_path):
306
331
  """A new file in a writable directory passes."""
307
332
  assert _argparse.check_output_file(tmp_path / "out.json", _parser()) is None
@@ -106,3 +106,94 @@ def test_init_logger_installs_next_to_a_foreign_handler(root_logger, tmp_path):
106
106
 
107
107
 
108
108
  # LocalWords: init py CifQL stderr
109
+
110
+
111
+ @pytest.mark.usefixtures("root_logger")
112
+ def test_log_to_file_writes_there_not_to_the_terminal(tmp_path, capsys):
113
+ """Once logging goes to a file, the terminal stays quiet."""
114
+ _logging.init_logger("INFO")
115
+ _logging.log_to_file(tmp_path / "s.log", 1024 * 1024, 2)
116
+
117
+ logging.getLogger("cifql.testing").info("hello")
118
+
119
+ assert re.fullmatch(
120
+ r"\d\d/\d\d/\d{4} \d\d:\d\d:\d\d - INFO \| hello\n",
121
+ (tmp_path / "s.log").read_text(encoding="utf8"),
122
+ )
123
+ assert capsys.readouterr().err == ""
124
+
125
+
126
+ def test_a_log_file_that_can_not_be_opened_keeps_the_terminal(tmp_path, capsys):
127
+ """The terminal handler goes only once the file is open."""
128
+ _logging.init_logger("INFO")
129
+ with pytest.raises(OSError):
130
+ _logging.log_to_file(tmp_path, 1024 * 1024, 2)
131
+
132
+ logging.getLogger("cifql.testing").error("still here")
133
+
134
+ assert "still here" in capsys.readouterr().err
135
+
136
+
137
+ @pytest.mark.usefixtures("root_logger")
138
+ def test_log_to_file_without_the_terminal_handler(tmp_path):
139
+ """Works when logging was not set up before, with CifQL's format."""
140
+ logging.getLogger().setLevel("INFO")
141
+ _logging.log_to_file(tmp_path / "s.log", 1024 * 1024, 2)
142
+
143
+ logging.getLogger("cifql.testing").info("hello")
144
+
145
+ assert " - INFO | hello" in (tmp_path / "s.log").read_text(encoding="utf8")
146
+
147
+
148
+ @pytest.mark.usefixtures("root_logger")
149
+ def test_errors_reach_the_terminal_until_the_server_is_up(tmp_path, capsys):
150
+ """A server that does not come up says why on the terminal; once it is
151
+ up, the file alone."""
152
+ _logging.init_logger("INFO")
153
+ _logging.log_to_file(tmp_path / "s.log", 1024 * 1024, 2)
154
+
155
+ logging.getLogger("cifql.testing").error("port in use")
156
+ assert "port in use" in capsys.readouterr().err
157
+ _logging.end_startup()
158
+ logging.getLogger("cifql.testing").error("later")
159
+
160
+ assert capsys.readouterr().err == ""
161
+ log = (tmp_path / "s.log").read_text(encoding="utf8")
162
+ assert "port in use" in log
163
+ assert "later" in log
164
+
165
+
166
+ @pytest.mark.usefixtures("root_logger")
167
+ def test_the_log_file_is_rotated(tmp_path):
168
+ """Full files are renamed, the oldest beyond the backups dropped."""
169
+ _logging.init_logger("INFO")
170
+ _logging.log_to_file(tmp_path / "s.log", 200, 2)
171
+
172
+ for i in range(50):
173
+ logging.getLogger("cifql.testing").info("line %d", i)
174
+
175
+ assert sorted(path.name for path in tmp_path.iterdir()) == [
176
+ "s.log",
177
+ "s.log.1",
178
+ "s.log.2",
179
+ ]
180
+
181
+
182
+ @pytest.mark.usefixtures("root_logger")
183
+ def test_init_logger_after_log_to_file_keeps_the_file(tmp_path, capsys):
184
+ """cifql's catch of an error sets up logging again, it stays in the
185
+ file."""
186
+ _logging.init_logger("INFO")
187
+ _logging.log_to_file(tmp_path / "s.log", 1024 * 1024, 2)
188
+ _logging.end_startup()
189
+
190
+ _logging.init_logger("INFO")
191
+ logging.getLogger("cifql.testing").info("still here")
192
+
193
+ assert "still here" in (tmp_path / "s.log").read_text(encoding="utf8")
194
+ assert capsys.readouterr().err == ""
195
+
196
+
197
+ def test_end_startup_without_a_log_file_does_nothing():
198
+ """No start-up handler, nothing to end."""
199
+ assert _logging.end_startup() is None