From 214d1e091bc8ae56805f5a57c6cc65231ec9c533 Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:42:17 +0800 Subject: [PATCH 1/2] feat(agent-tools): the knowledge-graph tools over Bolt and file.extract (RFC-0013 step 2) graph.schema, graph.query, graph.write and graph.ingest reach one graph database over the Bolt protocol (tools.graph.uri; the graph extra installs the official driver - Neo4j and Memgraph) in openCypher: the reads register when the URI is set, the writers only with tools.graph.write=true, DELETE and DROP refused unless tools.graph.delete=true. Every statement runs in a managed transaction with the configured timeout set server-side; a query is refused before sending when it carries a write clause outside a string or a comment; an ingest merges a model's extraction idempotently, every value a parameter, and checks the relationship endpoints inside the transaction. file.extract (PDF, Word, HTML, text with page markers) registers with the file tools when the documents extra is installed. dev/graph-up.sh runs Neo4j on Colima; 161 tests including a live round trip against it. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 17 + extensions/agent-tools/README.md | 96 +- extensions/agent-tools/agent_tools.py | 1075 ++++++++++++++++- .../agent-tools/catalog/file_extract.json | 27 + .../agent-tools/catalog/graph_ingest.json | 74 ++ .../agent-tools/catalog/graph_query.json | 22 + .../agent-tools/catalog/graph_schema.json | 11 + .../agent-tools/catalog/graph_write.json | 23 + extensions/agent-tools/dev/graph-down.sh | 5 + extensions/agent-tools/dev/graph-up.sh | 25 + .../agent-tools/resources/application.yml | 22 +- memory/continuity.md | 4 +- .../thread-bp-agent-tools-python.md | 9 +- memory/sessions/2026-11-17-101635.md | 2 +- memory/sessions/2026-11-17-104217.md | 60 + pyproject.toml | 9 + tests/test_agent_tools.py | 975 ++++++++++++++- 17 files changed, 2422 insertions(+), 34 deletions(-) create mode 100644 extensions/agent-tools/catalog/file_extract.json create mode 100644 extensions/agent-tools/catalog/graph_ingest.json create mode 100644 extensions/agent-tools/catalog/graph_query.json create mode 100644 extensions/agent-tools/catalog/graph_schema.json create mode 100644 extensions/agent-tools/catalog/graph_write.json create mode 100755 extensions/agent-tools/dev/graph-down.sh create mode 100755 extensions/agent-tools/dev/graph-up.sh create mode 100644 memory/sessions/2026-11-17-104217.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 52fb363..0f788f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,23 @@ served in-process with redirects to private and foreign hosts, the allowlist and address rules without a network). The knowledge-graph tools and `file.extract` follow as step 2, the Node.js twin as step 3. +3. **The knowledge-graph tools and `file.extract` complete the built-in agent tools' version 1 (RFC-0013 build plan + step 2).** `graph.schema`, `graph.query`, `graph.write` and `graph.ingest` reach one graph database over the Bolt + protocol (`tools.graph.uri`; the `graph` extra installs the official driver, which reaches Neo4j and Memgraph alike) + in openCypher: the reads register when the URI is set, the writers only with `tools.graph.write=true`, and `DELETE`, + `DETACH DELETE` and `DROP` are refused unless `tools.graph.delete=true`. The schema comes from the database's own + procedures (Neo4j's `db.schema.*`, else Memgraph's `schema.*`) with counts; a query runs in a read transaction, is + refused before sending when it carries a write clause outside a string or a comment, and returns its rows capped by + `tools.graph.max.rows` with nodes, relationships and paths rendered for the model; a write returns the counters; an + ingest merges a model's extraction - nodes by key and label, relationships between existing keys, every value a + parameter, `source` stamped on each - idempotently, in one transaction that checks the endpoints before any + relationship is written. Every statement carries the configured timeout server-side; a database failure comes back + by its own code as a 400 the model can act on, a timeout as a 408, an unreachable database as a 503 logged by type + only. `file.extract` (PDF and Word to text with page markers, a page range and a character cap; HTML and text files + too) registers with the file tools when the `documents` extra (`pypdf`, `python-docx`) is installed. + `dev/graph-up.sh` and `graph-down.sh` run Neo4j Community on Colima for development; the live test runs against it + when `TOOLS_GRAPH_TEST_URI` is set. The five new catalog rows join the `catalog/` folder and `describe`. + ### Fixed 1. **A direct `python extensions/mcp-binding/mcp_binding.py` now connects its servers.** The binding attached its boot diff --git a/extensions/agent-tools/README.md b/extensions/agent-tools/README.md index 09e7ba8..e03c043 100644 --- a/extensions/agent-tools/README.md +++ b/extensions/agent-tools/README.md @@ -1,8 +1,8 @@ # The built-in agent tools The essential tools every second agent use case needs - **files** inside one workspace, **the web** inside an allowlist -of sites, and **a clock** - as composable functions of a pack extension (RFC-0013 in the mercury-composable repository, -`draft-design-specs/agent-essential-tools.md`; the knowledge-graph tools and `file.extract` follow in the next step). A +of sites, **the agent's knowledge graph** inside one database, and **a clock** - as composable functions of a pack +extension (RFC-0013 in the mercury-composable repository, `draft-design-specs/agent-essential-tools.md`). A graph's agent loop (`llm.run` in the engines) names a route of this application in its tool catalog, the engine reaches the route through declarative Event-over-HTTP like any other function, and the model's arguments arrive as the event body. The loop, the catalog and the graph see nothing special about a built-in tool: **a route names the capability** @@ -26,7 +26,8 @@ The Node.js twin (mercury-nodejs `extensions/agent-tools`) serves the same route ## Run ```bash -pip install mercury-composable # no extra: files, web and clock add no dependency +pip install mercury-composable # files, web and clock add no dependency +pip install 'mercury-composable[graph,documents]' # + the Bolt driver (graph.*) and PDF/Word reading (file.extract) mercury-serve extensions/agent-tools/agent_tools.py -Dtools.file.root=/srv/workspace -Dtools.web.allow=docs.example.com python extensions/agent-tools/agent_tools.py # the same without mercury-serve ``` @@ -38,12 +39,17 @@ default (`rest.server.port`). Its boot log says what registered: ```text File tools registered - workspace /srv/workspace Web tools registered - 1 allowed site pattern(s) -Built-in tools ready - file.read, file.write, file.list, file.search, web.fetch, web.crawl, time.now +Graph tools registered - bolt://127.0.0.1:7687, writes allowed +Built-in tools ready - file.read, file.write, file.list, file.search, file.extract, web.fetch, web.crawl, graph.schema, graph.query, graph.write, graph.ingest, time.now ``` Without `tools.file.root` the file tools stay out (`File tools not registered - tools.file.root is not set`); without -`tools.web.allow` the web tools stay out; `time.now` registers unless `tools.time=false`. A root that is not a -directory, an allowlist entry that is not a host pattern or a limit that is not a number stops the application by name. +`tools.web.allow` the web tools stay out; without `tools.graph.uri` the graph tools stay out, and the two graph writers +need `tools.graph.write=true` as well; `file.extract` registers with the file tools when the `documents` extra is +installed; `time.now` registers unless `tools.time=false`. A root that is not a directory, an allowlist entry that is +not a host pattern, a graph URI that is not a Bolt URI or without the driver installed, or a limit that is not a number +stops the application by name. A graph database that does not answer at boot is logged, and its tools answer 503 until +it does. ## The tools @@ -62,8 +68,10 @@ the tree. | `file.list` | `file_list` | `path` (a folder, default `.`); `glob` (optional, `*.md` or `**/*.md`); `max_entries` (default 200, cap 2000) | `{entries: [{path, type, bytes, modified}], truncated}`, sorted by path; `type` is `file`, `directory` or `other`; `modified` in UTC | | `file.search` | `file_search` | `pattern` (required; a literal, or a regular expression with `regex: true`); `path` (default `.`); `glob` (default `**/*`); `case_sensitive` (default false); `context` (default 0, cap 3); `max_results` (default 100, cap 1000) | `{matches: [{path, line, text, before, after}], files_searched, truncated}`; text files only, binaries skipped, each line cut to `tools.file.line.max.chars` (500) | -`file.write` carries the write mark, so under the node's default mode a person approves it; the other three are reads -and run unasked. +| `file.extract` | `file_extract` | `path` (required); `pages` (a range such as `1-3,7`, default all); `max_chars` (default and cap `tools.file.extract.max.chars`, 60 000) | `{path, type, pages, text, truncated}`; `type` is `pdf`, `docx`, `html` or `text`, `pages` the document's page count, the text carries a `--- page N ---` marker before each page; a PDF or Word document needs the `documents` extra (`pypdf`, `python-docx`), without which the tool does not register; an encrypted PDF or another format is a 400 | + +`file.write` carries the write mark, so under the node's default mode a person approves it; the other file tools are +reads and run unasked. ### The web, inside an allowlist @@ -86,6 +94,36 @@ include prefix and the delay are all limits, and a model that needs more asks ag by a small in-house parser (no dependency), enough for documentation and articles; an installation whose pages need main-content extraction may put a library behind the same route. +### The knowledge graph, inside one database + +The agent's own store for what it extracts - documents ingested once, their entities, relations and rules queried many +times (the design's principle 7: extract once, query many). The sandbox is one database, `tools.graph.uri` (a Bolt +URI: `bolt://`, `bolt+s://`, `neo4j://`, `neo4j+s://`), `tools.graph.database` and the credential by reference +(`tools.graph.username`, `tools.graph.password: ${GRAPH_PASSWORD}`); the `graph` extra installs the official driver, +which reaches Neo4j and Memgraph alike. The query language is openCypher. The two reads register when the URI is set; +the two writers only when `tools.graph.write=true`, and `DELETE`, `DETACH DELETE` and `DROP` are refused unless +`tools.graph.delete=true` as well. Every statement runs in a managed transaction with `tools.graph.timeout.ms` set +server-side, a read in a read transaction, so a statement that writes fails even if the clause scan missed it. + +| Route | Row | Arguments | Result | +| --- | --- | --- | --- | +| `graph.schema` | `graph_schema` | none | `{labels: [{label, count, properties: [{name, types}]}], relationship_types: [{type, count, from, to, properties}]}` from the database's own schema procedures (Neo4j's `db.schema.*`, else Memgraph's `schema.*`) and two counting queries; what the model reads before it writes a query or an ingest | +| `graph.query` | `graph_query` | `query` (openCypher, read-only, required); `parameters` (a map) | `{columns, rows, truncated}`; refused before sending when it carries `CREATE`, `MERGE`, `SET`, `DELETE`, `REMOVE`, `DROP` or `LOAD CSV` outside a string or a comment; rows capped by `tools.graph.max.rows` (200, cap 2000); a node rendered `{id, labels, properties}`, a relationship `{id, type, start, end, properties}`, a path as the list of its nodes and relationships, temporal values as text, points as `{srid, coordinates}` | +| `graph.write` | `graph_write`, **`write: true`** | `query`, `parameters` | `{counters: {nodes_created, nodes_deleted, relationships_created, relationships_deleted, properties_set, labels_added, labels_removed, indexes_added, constraints_added}, columns, rows, truncated}` from a write transaction | +| `graph.ingest` | `graph_ingest`, **`write: true`** | `nodes: [{key, label, properties}]`, `relationships: [{from, to, type, properties}]`, `source` (optional) | `{nodes, relationships}` counts: one parameterized `MERGE` per label on `(:Label {key})` with `SET n += properties`, one per type between two keys that exist (in this call or already in the graph - a missing endpoint is a 400 naming the key, and nothing is written), `source` stamped on every node and relationship; labels and types `^[A-Za-z][A-Za-z0-9_]{0,63}$`, values scalars or lists of scalars, at most `tools.graph.ingest.max.nodes` (500) nodes and four times as many relationships per call; running it twice changes nothing | + +Why `graph.ingest` beside `graph.write`: a list of nodes and relationships is what a model extracts well, and a long +`MERGE` with dozens of parameters is where Cypher goes wrong. The tool makes the Cypher, no value is ever interpolated +into a statement, and the write is idempotent. The row's description tells the model the conventions: a key unique +across the graph, prefixed with the label in lower case (`clause:12`, `party:supplier-a`); a `source` on every ingest +so an answer can cite it. A database failure comes back by the database's own code (`Neo.ClientError.Statement.SyntaxError: +...`) as a 400 the model can act on; a transaction over the timeout is a 408; an unreachable database or a refused +credential a 503, logged by type only. + +For development, `dev/graph-up.sh` starts Neo4j Community on Colima with its Browser at `http://127.0.0.1:7474` +(`GRAPH_PASSWORD=... extensions/agent-tools/dev/graph-up.sh`; `graph-down.sh` removes it), and the live test runs +against it when `TOOLS_GRAPH_TEST_URI` and `TOOLS_GRAPH_TEST_PASSWORD` are set. + ### The clock `time.now` (`time_now`) takes an optional `timezone` (an IANA name, default `UTC`) and returns @@ -108,6 +146,15 @@ time zone database (some containers) needs the `tzdata` package for any zone but | `tools.web.crawl.max.pages` | `50` | the most pages one crawl may ask for; the tool's cap, a deployment may lower it | | `tools.web.crawl.delay.ms` | `500` | the pause between two requests of a crawl | | `tools.web.page.max.chars` | `20000` | the characters kept of a page's text | +| `tools.file.extract.max.chars` | `60000` | the most characters `file.extract` returns | +| `tools.graph.uri` | unset | the graph database, a Bolt URI; unset, the graph tools do not register | +| `tools.graph.database` | the server's default | the database name | +| `tools.graph.username`, `tools.graph.password` | unset | the credential, by reference (`${GRAPH_PASSWORD}`); never logged | +| `tools.graph.write` | `false` | register `graph.write` and `graph.ingest` | +| `tools.graph.delete` | `false` | allow `DELETE` and `DROP` in `graph.write` | +| `tools.graph.max.rows` | `200` | the most rows a query returns (the tool's cap is 2000) | +| `tools.graph.timeout.ms` | `10000` | how long one transaction may take, set server-side | +| `tools.graph.ingest.max.nodes` | `500` | the most nodes one `graph.ingest` call may carry (relationships: four times as many) | | `tools.time` | `true` | register `time.now` | Limits are defaults a deployment lowers, never raises past the tool's caps (a `tools.web.crawl.max.pages` above 50 is @@ -120,11 +167,12 @@ logged and capped). The shipped `application.yml` takes the root and the allowli | --- | --- | | Request | The event body is the tool's arguments, a map of the row's properties. Anything else, an unknown argument or a wrong type is a 400 naming it. | | Reply | The result map of the table above. | -| 400 | A refusal by rule: a path outside the workspace, a hidden entry, a binary file, a site that is not allowed, a private address, a bad argument, too many redirects, a response that is not text. The message names the rule and the key that governs it. | +| 400 | A refusal by rule: a path outside the workspace, a hidden entry, a binary file, a site that is not allowed, a private address, a bad argument, too many redirects, a response that is not text, a write clause in a read-only query, a deletion without the gate, an ingest with a bad label or a missing endpoint; or the graph database's own client error, by its code. The message names the rule and the key that governs it. | | 404 | The file or folder does not exist. | -| 408 | The site did not answer within `tools.web.timeout.ms`. | +| 408 | The site or the graph database did not answer within its timeout. | | 409 | `file.write` in `create` mode found the file. | -| 502 | The host cannot be resolved or the connection failed. | +| 502 | The host cannot be resolved, the connection failed, or the graph database failed in a way that is not the caller's. | +| 503 | The graph database is not reachable or refused this process's credential. | A Java or Rust engine maps the routes in its `yaml.event.over.http` file to this application's `/api/event`, and a graph's catalog row names the route: @@ -132,13 +180,15 @@ graph's catalog row names the route: ```yaml event: http: - - route: 'file.read, file.write, file.list, file.search, web.fetch, web.crawl, time.now' + - route: 'file.read, file.write, file.list, file.search, file.extract, web.fetch, web.crawl' + target: 'http://127.0.0.1:8089/api/event' + - route: 'graph.schema, graph.query, graph.write, graph.ingest, time.now' target: 'http://127.0.0.1:8089/api/event' ``` **Logs.** A tool logs its route, the status, the byte, entry or page count and the host of a URL - never a path's -content, a page's text or a full URL (a query string may carry a token). The engines' trace names the route like any -function's. +content, a page's text, a full URL (a query string may carry a token), a query's parameters or a graph credential. The +engines' trace names the route like any function's. ## The catalog rows @@ -174,15 +224,19 @@ files. A catalog node on a graph takes them as its `tools` list: ## Health -`tools.health` (the `/health` actuator, `mandatory.health.dependencies`) reports the registered routes, the workspace -and the allowed site patterns - the answer to "what can this agent reach?" without reading code. +`tools.health` (the `/health` actuator, `mandatory.health.dependencies`) reports the registered routes, the workspace, +the allowed site patterns and the graph database's address (never its credential) - the answer to "what can this agent +reach?" without reading code. ## Security - **The catalog is still the boundary.** A graph names the tools its agent reaches; a built-in the graph does not name is as unreachable as any route, and a deployment whose sandbox is not configured fails the graph's pre-flight check before a token is spent. -- **The root, the allowlist and the private-address gate are certification artifacts**, reviewed with the deployment. +- **The root, the allowlist, the private-address gate and the graph's two gates are certification artifacts**, reviewed + with the deployment. Writing the graph needs `tools.graph.write=true`; deleting needs `tools.graph.delete=true` as + well; a read runs in a read transaction; an ingest is parameters only, and a label or type that is not an identifier + is refused. - **No shell, no arbitrary request.** A URL the model chooses is checked by host, scheme, port, resolved address and on every redirect; a path the model chooses is resolved and checked against the root. There is no generic `http.request` and no command execution, by design. @@ -199,5 +253,9 @@ pytest tests/test_agent_tools.py The file tools run against a workspace built in a temporary directory (a link that escapes it, hidden entries, a binary, a file that is not UTF-8, a large file); the HTML reader against a fixture page; the allowlist and the address rules without a network; the web tools against a small site served in-process by aiohttp (pages that link each -other, `robots.txt`, redirects to allowed, private and foreign hosts, a slow page, a large body, charsets); the boot, -the health route, the `describe` output and the catalog files complete the suite. +other, `robots.txt`, redirects to allowed, private and foreign hosts, a slow page, a large body, charsets); the graph +tools against a fake backend that scripts the rows (the schema from Neo4j's and from Memgraph's procedures, the clause +scan, the row cap, the delete gate, the ingest's statement order and its endpoint check) and the pure half (rendering, +the clause scan, the ingest plan, the error mapping on the driver's own exception classes); `file.extract` on a PDF and +a Word document generated in the test; the boot, the health route, the `describe` output and the catalog files complete +the suite. The live graph test runs when `TOOLS_GRAPH_TEST_URI` names a database. diff --git a/extensions/agent-tools/agent_tools.py b/extensions/agent-tools/agent_tools.py index 549fbba..f8e253c 100644 --- a/extensions/agent-tools/agent_tools.py +++ b/extensions/agent-tools/agent_tools.py @@ -16,6 +16,12 @@ ``web.crawl``), over https unless a host is listed with ``http://``; an address in a loopback, private, link-local or multicast range is refused unless ``tools.web.allow.private=true``, and every redirect is checked again. +- ``tools.graph.uri`` names the one graph database the four knowledge-graph tools reach over the + Bolt protocol (``graph.schema``, ``graph.query`` in a read transaction; ``graph.write`` and + ``graph.ingest`` only when ``tools.graph.write=true``, deletion only when ``tools.graph.delete=true``); + the ``graph`` extra installs the driver. +- ``file.extract`` (PDF and Word documents to text) registers with the file tools when the + ``documents`` extra is installed. - ``time.now`` reads nothing and registers unless ``tools.time=false``. A tool whose sandbox is not configured does not register, so an unconfigured tool is a 404 to the @@ -39,14 +45,18 @@ from __future__ import annotations import asyncio +import base64 import fnmatch +import io import ipaddress import json import re import socket import sys import urllib.robotparser +import zipfile from collections import deque +from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import datetime, timezone from html.parser import HTMLParser @@ -57,6 +67,24 @@ import aiohttp +try: + import neo4j + from neo4j import exceptions as neo4j_errors +except ( + ImportError +): # the graph tools register only with the driver - pip install 'mercury-composable[graph]' + neo4j = None + neo4j_errors = None + +try: + import docx + import pypdf +except ( + ImportError +): # file.extract registers only with the libraries - pip install 'mercury-composable[documents]' + docx = None + pypdf = None + from mercury_composable import ( AppException, Body, @@ -115,6 +143,49 @@ REDIRECT_STATUSES = (301, 302, 303, 307, 308) FETCH_MODES = ("text", "markdown", "raw") +# documents: file.extract +FILE_EXTRACT_MAX_CHARS = "tools.file.extract.max.chars" +DEFAULT_EXTRACT_MAX_CHARS = 60000 +DOCUMENTS_EXTRA = "pip install 'mercury-composable[documents]'" + +# the knowledge graph: one database over Bolt +GRAPH_URI = "tools.graph.uri" +GRAPH_DATABASE = "tools.graph.database" +GRAPH_USERNAME = "tools.graph.username" +GRAPH_PASSWORD = "tools.graph.password" +GRAPH_WRITE = "tools.graph.write" +GRAPH_DELETE = "tools.graph.delete" +GRAPH_MAX_ROWS = "tools.graph.max.rows" +GRAPH_TIMEOUT_MS = "tools.graph.timeout.ms" +GRAPH_INGEST_MAX_NODES = "tools.graph.ingest.max.nodes" +GRAPH_EXTRA = "pip install 'mercury-composable[graph]'" +ROWS_DEFAULT, ROWS_CAP = 200, 2000 +DEFAULT_GRAPH_TIMEOUT_MS = 10000 +DEFAULT_INGEST_MAX_NODES = 500 +# a call may carry this many relationships per allowed node - the tool's own bound +INGEST_RELATIONSHIPS_PER_NODE = 4 +IDENTIFIER = re.compile(r"[A-Za-z][A-Za-z0-9_]{0,63}") +PROPERTY_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,63}") +# the clauses a read-only query may not carry, and the ones the delete gate guards +WRITE_CLAUSES = re.compile(r"\b(CREATE|MERGE|SET|DELETE|REMOVE|DROP|LOAD\s+CSV)\b", re.IGNORECASE) +DELETE_CLAUSES = re.compile(r"\b(DELETE|DROP)\b", re.IGNORECASE) +# string literals, quoted identifiers and comments, blanked before a query is scanned for clauses +CYPHER_LITERALS = re.compile( + r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"|`[^`]*`|//[^\n]*|/\*.*?\*/", re.DOTALL +) +KEY_MAX_CHARS = 512 +COUNTER_NAMES = ( + "nodes_created", + "nodes_deleted", + "relationships_created", + "relationships_deleted", + "properties_set", + "labels_added", + "labels_removed", + "indexes_added", + "constraints_added", +) + # the clock TIME_ENABLED = "tools.time" @@ -327,6 +398,134 @@ def _row( ["url"], ) +FILE_EXTRACT_ROW = _row( + "file_extract", + "file.extract", + "Extract the text of a PDF or Word document in the agent's workspace (an HTML or plain text file works too), " + "with a marker before each page (--- page N ---). path is relative to the workspace root; pages selects a " + "range such as 1-3,7 (default: all pages); the text is cut at max_chars. Returns the path, the document type, " + "the number of pages the document has and the text. Use file_read for a plain text file.", + { + "path": {"type": "string", "description": "The document, relative to the workspace root."}, + "pages": { + "type": "string", + "description": "The pages to extract, 1-based, such as 1-3,7; default: all.", + }, + "max_chars": { + "type": "integer", + "minimum": 100, + "description": "Return at most this many characters (default and cap: the workspace's limit).", + }, + }, + ["path"], +) + +GRAPH_SCHEMA_ROW = _row( + "graph_schema", + "graph.schema", + "The schema of the agent's knowledge graph: every node label with its count and its property names and types, " + "and every relationship type with its count and the labels it connects. Read it before writing a query or an " + "ingest, so labels, types and property names match what the graph holds.", + {}, + [], +) + +GRAPH_QUERY_ROW = _row( + "graph_query", + "graph.query", + "Run a read-only openCypher query against the agent's knowledge graph and return its rows. Pass values as " + "parameters ($name in the query, the value under that name in parameters) instead of writing them into the " + "query. A node comes back as {id, labels, properties}, a relationship as {id, type, start, end, properties}, a " + "path as a list of them. Rows are capped: narrow the query with WHERE and LIMIT when the result was cut. A query " + "that writes (CREATE, MERGE, SET, DELETE, REMOVE, DROP, LOAD CSV) is refused - use graph_write or graph_ingest.", + { + "query": { + "type": "string", + "description": "The openCypher query, read-only, with $parameters.", + }, + "parameters": {"type": "object", "description": "The values the query's $parameters take."}, + }, + ["query"], +) + +GRAPH_WRITE_ROW = _row( + "graph_write", + "graph.write", + "Run an openCypher statement that changes the agent's knowledge graph - an index or a constraint, a corrected " + "property, a relationship between existing nodes - and return the counters of what changed. Pass every value as " + "a parameter. DELETE and DROP are refused unless the deployment allows deletion. To load extracted entities " + "and relations, prefer graph_ingest, which merges them idempotently.", + { + "query": {"type": "string", "description": "The openCypher statement, with $parameters."}, + "parameters": { + "type": "object", + "description": "The values the statement's $parameters take.", + }, + }, + ["query"], + write=True, +) + +GRAPH_INGEST_ROW = _row( + "graph_ingest", + "graph.ingest", + "Load what you extracted from a document into the agent's knowledge graph, idempotently. Each node is merged " + "on its key - unique across the graph, the label in lower case as its prefix (clause:12, party:supplier-a) - " + "with its label and properties; each relationship is merged between two keys that exist (in this call or " + "already in the graph) with its type and properties. Labels and types are identifiers (letters, digits and " + "underscore, starting with a letter); property values are scalars or lists of scalars. Give source (the " + "document's path or URL) so an answer can cite it. Running the same ingest twice changes nothing.", + { + "nodes": { + "type": "array", + "description": "The entities: a key, a label and properties each.", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "Unique across the graph, prefixed with the label.", + }, + "label": {"type": "string", "description": "The node's label, an identifier."}, + "properties": { + "type": "object", + "description": "Scalar or list-of-scalar values by name.", + }, + }, + "required": ["key", "label"], + "additionalProperties": False, + }, + }, + "relationships": { + "type": "array", + "description": "The relations: from a key to a key, with a type and properties.", + "items": { + "type": "object", + "properties": { + "from": {"type": "string", "description": "The key of the start node."}, + "to": {"type": "string", "description": "The key of the end node."}, + "type": { + "type": "string", + "description": "The relationship type, an identifier.", + }, + "properties": { + "type": "object", + "description": "Scalar or list-of-scalar values by name.", + }, + }, + "required": ["from", "to", "type"], + "additionalProperties": False, + }, + }, + "source": { + "type": "string", + "description": "The document the facts come from - its path or URL.", + }, + }, + [], + write=True, +) + TIME_NOW_ROW = _row( "time_now", "time.now", @@ -344,8 +543,13 @@ def _row( FILE_WRITE_ROW, FILE_LIST_ROW, FILE_SEARCH_ROW, + FILE_EXTRACT_ROW, WEB_FETCH_ROW, WEB_CRAWL_ROW, + GRAPH_SCHEMA_ROW, + GRAPH_QUERY_ROW, + GRAPH_WRITE_ROW, + GRAPH_INGEST_ROW, TIME_NOW_ROW, ) ROW_BY_ROUTE: dict[str, dict[str, Any]] = {row["route"]: row for row in ROWS} @@ -477,6 +681,7 @@ class FileSandbox: hidden: bool = False write_extensions: tuple[str, ...] = () line_max_chars: int = DEFAULT_LINE_MAX_CHARS + extract_max_chars: int = DEFAULT_EXTRACT_MAX_CHARS def load_file_sandbox() -> FileSandbox | None: @@ -498,6 +703,9 @@ def load_file_sandbox() -> FileSandbox | None: hidden=_bool_setting(FILE_HIDDEN, False), write_extensions=extensions, line_max_chars=_int_setting(FILE_LINE_MAX_CHARS, DEFAULT_LINE_MAX_CHARS, floor=20), + extract_max_chars=_int_setting( + FILE_EXTRACT_MAX_CHARS, DEFAULT_EXTRACT_MAX_CHARS, floor=100 + ), ) @@ -789,6 +997,163 @@ def search(self, _headers: dict[str, str], body: Body) -> Any: ) return {"matches": matches, "files_searched": searched, "truncated": truncated} + # -- file.extract: documents to text, behind the documents extra + + def extract(self, _headers: dict[str, str], body: Body) -> Any: + args = _arguments(body, FILE_EXTRACT_ROW) + path = _string(args, "path") + pages_spec = args.get("pages") + if pages_spec is not None and not isinstance(pages_spec, str): + raise AppException(400, "pages must be a string such as 1-3,7") + limit = _integer( + args, + "max_chars", + default=self.sandbox.extract_max_chars, + floor=100, + cap=self.sandbox.extract_max_chars, + ) + target, relative = self.resolve(path) + if target.is_dir(): + raise AppException(400, f"{relative} is a directory - name a document") + if not target.is_file(): + raise AppException(404, f"file not found: {relative}") + data = target.read_bytes() + kind = document_kind(data, target.suffix) + if kind is None: + raise AppException( + 400, + f"{relative} is not a PDF, Word, HTML or text document " + f"({binary_kind(data[:8192]) or 'unknown format'})", + ) + if kind == "pdf": + pages = _pdf_pages(data, relative) + elif kind == "docx": + pages = [_docx_text(data, relative)] + elif kind == "html": + pages = [html_to_text(data.decode("utf-8", errors="replace"))[1]] + else: + text = decode_utf8(data, truncated=False) + if text is None: + raise AppException(400, f"{relative} is not UTF-8 text") + pages = [text] + wanted = page_range(pages_spec, len(pages)) + parts = [f"--- page {number} ---\n{pages[number - 1].strip()}" for number in wanted] + text = "\n\n".join(parts) + truncated = len(text) > limit + log.info( + "file.extract 200 %s, %d of %d pages, %d chars%s", + kind, + len(wanted), + len(pages), + min(len(text), limit), + " (cut)" if truncated else "", + ) + return { + "path": relative, + "type": kind, + "pages": len(pages), + "text": text[:limit], + "truncated": truncated, + } + + +# --- documents to text ---------------------------------------------------------------------------- + + +def documents_available() -> bool: + """Whether the ``documents`` extra is installed - pypdf and python-docx.""" + return pypdf is not None and docx is not None + + +def document_kind(data: bytes, suffix: str) -> str | None: + """``pdf``, ``docx``, ``html`` or ``text`` from the first bytes and the suffix; ``None`` for a + format the tool does not read.""" + if data.startswith(b"%PDF"): + return "pdf" + if data.startswith(b"PK\x03\x04"): + try: + with zipfile.ZipFile(io.BytesIO(data)) as archive: + return "docx" if "word/document.xml" in archive.namelist() else None + except zipfile.BadZipFile: + return None + if binary_kind(data[:8192]) is not None: + return None + head = data[:2048].lstrip().lower() + if suffix.lower() in (".html", ".htm", ".xhtml") or head.startswith( + (b" list[int]: + """``1-3,7`` to the 1-based page numbers inside the document, in order and without repeats; + an empty selection means every page.""" + if total <= 0: + return [] + if spec is None or not spec.strip(): + return list(range(1, total + 1)) + wanted: list[int] = [] + for token in spec.split(","): + part = token.strip() + if not part: + continue + first, dash, last = part.partition("-") + try: + start = int(first) + end = int(last) if dash else start + except ValueError as exc: + raise AppException(400, "pages must be page numbers and ranges such as 1-3,7") from exc + if start < 1 or end < start: + raise AppException( + 400, "pages must be page numbers and ranges such as 1-3,7, counted from 1" + ) + for number in range(start, min(end, total) + 1): + if number not in wanted: + wanted.append(number) + return wanted + + +def _pdf_pages(data: bytes, relative: str) -> list[str]: + assert pypdf is not None + try: + reader = pypdf.PdfReader(io.BytesIO(data), strict=False) + if reader.is_encrypted: + try: + opened = reader.decrypt("") + except Exception as exc: # any failure to open means the document stays closed + raise AppException(400, f"{relative} is an encrypted PDF") from exc + if not opened: + raise AppException(400, f"{relative} is an encrypted PDF") + return [page.extract_text() or "" for page in reader.pages] + except AppException: + raise + except Exception as exc: # the library's own failure, named by type to the model + raise AppException( + 400, f"{relative} could not be read as a PDF ({type(exc).__name__})" + ) from exc + + +def _docx_text(data: bytes, relative: str) -> str: + assert docx is not None + try: + document = docx.Document(io.BytesIO(data)) + blocks: list[str] = [] + for item in document.iter_inner_content(): + rows = getattr(item, "rows", None) + if rows is None: + text = str(getattr(item, "text", "")).strip() + if text: + blocks.append(text) + continue + lines = [" | ".join(cell.text.strip() for cell in row.cells) for row in rows] + blocks.append("\n".join(line for line in lines if line.strip(" |"))) + return "\n\n".join(blocks) + except Exception as exc: # the library's own failure, named by type to the model + raise AppException( + 400, f"{relative} could not be read as a Word document ({type(exc).__name__})" + ) from exc + # --- HTML to text, in-house ---------------------------------------------------------------------- @@ -1532,6 +1897,659 @@ async def web_crawl(self, _headers: dict[str, str], body: Body) -> Any: return {"pages": pages, "visited": visited, "truncated": truncated} +# --- the knowledge graph, inside one database ------------------------------------------------------- + + +@dataclass(frozen=True) +class GraphSandbox: + """One graph database over Bolt and the limits of the tools inside it; the credential is held + for the driver and never logged.""" + + uri: str + database: str | None = None + username: str | None = None + password: str | None = None + write: bool = False + delete: bool = False + max_rows: int = ROWS_DEFAULT + timeout_ms: int = DEFAULT_GRAPH_TIMEOUT_MS + ingest_max_nodes: int = DEFAULT_INGEST_MAX_NODES + + @property + def address(self) -> str: + """The URI without its credential - what a log or a health report may show.""" + parts = urlsplit(self.uri) + return urlunsplit((parts.scheme, parts.netloc.rsplit("@", 1)[-1], "", "", "")) + + +def load_graph_sandbox() -> GraphSandbox | None: + """The graph tools' sandbox from the configuration - ``None`` when ``tools.graph.uri`` is not + set, so the graph tools do not register; a URI without the driver stops the boot by name.""" + uri = _setting(GRAPH_URI) + if uri is None: + return None + if neo4j is None: + raise ToolsError(f"{GRAPH_URI} is set but the Bolt driver is not installed - {GRAPH_EXTRA}") + scheme = urlsplit(str(uri)).scheme.lower() + if not scheme.startswith(("bolt", "neo4j")): + raise ToolsError( + f"{GRAPH_URI} must be a Bolt URI (bolt://, bolt+s://, neo4j://, neo4j+s://), not {uri}" + ) + username = _setting(GRAPH_USERNAME) + password = _setting(GRAPH_PASSWORD) + database = _setting(GRAPH_DATABASE) + return GraphSandbox( + uri=str(uri), + database=None if database is None else str(database), + username=None if username is None else str(username), + password=None if password is None else str(password), + write=_bool_setting(GRAPH_WRITE, False), + delete=_bool_setting(GRAPH_DELETE, False), + max_rows=_int_setting(GRAPH_MAX_ROWS, ROWS_DEFAULT, cap=ROWS_CAP), + timeout_ms=_int_setting( + GRAPH_TIMEOUT_MS, DEFAULT_GRAPH_TIMEOUT_MS, floor=MIN_WEB_TIMEOUT_MS + ), + ingest_max_nodes=_int_setting(GRAPH_INGEST_MAX_NODES, DEFAULT_INGEST_MAX_NODES), + ) + + +@dataclass +class Rows: + """What one statement returned: the column names, the rows as raw driver values (cut at a + limit), whether they were cut, and the summary counters.""" + + columns: list[str] + values: list[list[Any]] + truncated: bool = False + counters: dict[str, int] | None = None + + +class Transaction: + """The statements of one transaction, run by a backend: the real one wraps the driver's managed + transaction; the tests' fake scripts the rows. ``run`` returns the rows and the counters.""" + + async def run( + self, query: str, parameters: dict[str, Any] | None = None, *, limit: int | None = None + ) -> Rows: + raise NotImplementedError + + +Work = Callable[[Transaction], Awaitable[Any]] + + +class BoltTransaction(Transaction): + def __init__(self, tx: Any): + self._tx = tx + + async def run( + self, query: str, parameters: dict[str, Any] | None = None, *, limit: int | None = None + ) -> Rows: + result = await self._tx.run(query, parameters or {}) + columns = list(result.keys()) + values: list[list[Any]] = [] + truncated = False + async for record in result: + if limit is not None and len(values) >= limit: + truncated = True + break + values.append(list(record.values())) + summary = await result.consume() + counters = summary.counters + return Rows( + columns, + values, + truncated, + {name: int(getattr(counters, name, 0) or 0) for name in COUNTER_NAMES}, + ) + + +class Bolt: + """The real backend: the official driver, one connection pool for the process, every statement + inside a managed transaction with the configured timeout set server-side.""" + + def __init__(self, sandbox: GraphSandbox): + assert neo4j is not None + self.sandbox = sandbox + auth = (sandbox.username or "", sandbox.password or "") if sandbox.username else None + self._driver = neo4j.AsyncGraphDatabase.driver( + sandbox.uri, auth=auth, connection_timeout=sandbox.timeout_ms / 1000 + ) + + async def verify(self) -> None: + await self._driver.verify_connectivity() + + async def close(self) -> None: + await self._driver.close() + + def _session(self, *, write: bool) -> Any: + assert neo4j is not None + mode = neo4j.WRITE_ACCESS if write else neo4j.READ_ACCESS + if self.sandbox.database: + return self._driver.session(database=self.sandbox.database, default_access_mode=mode) + return self._driver.session(default_access_mode=mode) + + async def execute(self, work: Work, *, write: bool) -> Any: + assert neo4j is not None + + async def function(tx: Any) -> Any: + return await work(BoltTransaction(tx)) + + managed = neo4j.unit_of_work(timeout=self.sandbox.timeout_ms / 1000)(function) + async with self._session(write=write) as session: + if write: + return await session.execute_write(managed) + return await session.execute_read(managed) + + +def graph_error(exc: BaseException, *, timeout_ms: int) -> AppException: + """The driver's failure as the tool's status: a client error (syntax, type, constraint, a write + in a read transaction) is a 400 carrying the database's code and message for the model; a + transaction that timed out a 408; an unreachable database or a refused credential a 503; the + rest a 502 by type. Never the parameters.""" + if isinstance(exc, AppException): + return exc + if isinstance(exc, asyncio.TimeoutError): + return AppException(408, f"the graph database did not answer within {timeout_ms} ms") + name = type(exc).__name__ + if neo4j_errors is not None: + if isinstance(exc, neo4j_errors.Neo4jError): + code = str(exc.code or "") + message = str(exc.message or exc) + if "TimedOut" in code or "Timeout" in code: + return AppException( + 408, f"the graph database did not answer within {timeout_ms} ms ({code})" + ) + if isinstance(exc, neo4j_errors.AuthError): + return AppException(503, "the graph database refused this process's credential") + if isinstance(exc, (neo4j_errors.TransientError, neo4j_errors.DatabaseUnavailable)): + return AppException(503, f"the graph database is not available ({code})") + if isinstance(exc, neo4j_errors.ClientError): + return AppException(400, f"{code}: {message}") + return AppException(502, f"the graph database failed ({code})") + if isinstance( + exc, + ( + neo4j_errors.ServiceUnavailable, + neo4j_errors.SessionExpired, + neo4j_errors.ConnectionAcquisitionTimeoutError, + ), + ): + return AppException(503, f"the graph database is not reachable ({name})") + return AppException(502, f"the graph database failed ({name})") + + +def render_value(value: Any) -> Any: + """A driver value as JSON for the model: a node ``{id, labels, properties}``, a relationship + ``{id, type, start, end, properties}``, a path as the list of its nodes and relationships in + order, temporal and spatial values as text and ``{srid, coordinates}``, bytes as base64.""" + if value is None or isinstance(value, (bool, int, float, str)): + return value + if isinstance(value, (bytes, bytearray)): + return base64.b64encode(bytes(value)).decode("ascii") + if isinstance(value, dict): + return {str(key): render_value(item) for key, item in value.items()} + if hasattr(value, "nodes") and hasattr(value, "relationships") and not hasattr(value, "labels"): + rendered: list[Any] = [] + nodes = list(value.nodes) + relationships = list(value.relationships) + for index, node in enumerate(nodes): + rendered.append(render_value(node)) + if index < len(relationships): + rendered.append(render_value(relationships[index])) + return rendered + if hasattr(value, "type") and hasattr(value, "start_node") and hasattr(value, "element_id"): + return { + "id": str(value.element_id), + "type": str(value.type), + "start": str(value.start_node.element_id), + "end": str(value.end_node.element_id), + "properties": {str(key): render_value(item) for key, item in value.items()}, + } + if hasattr(value, "labels") and hasattr(value, "element_id"): + return { + "id": str(value.element_id), + "labels": sorted(str(label) for label in value.labels), + "properties": {str(key): render_value(item) for key, item in value.items()}, + } + if hasattr(value, "srid") and isinstance(value, tuple): + return {"srid": getattr(value, "srid"), "coordinates": [float(c) for c in value]} # noqa: B009 + if hasattr(value, "iso_format"): + return value.iso_format() + if isinstance(value, (list, tuple, set, frozenset)): + return [render_value(item) for item in value] + return str(value) + + +def strip_cypher_literals(query: str) -> str: + """The query with its string literals, quoted identifiers and comments blanked, so a clause + scan never fires on a word inside a string.""" + return CYPHER_LITERALS.sub(" ", query) + + +def write_clause(query: str) -> str | None: + """The first write clause a query carries, upper-cased, or ``None`` for a read.""" + match = WRITE_CLAUSES.search(strip_cypher_literals(query)) + return re.sub(r"\s+", " ", match.group(1).upper()) if match else None + + +def delete_clause(query: str) -> str | None: + match = DELETE_CLAUSES.search(strip_cypher_literals(query)) + return match.group(1).upper() if match else None + + +def _scalar(value: Any) -> bool: + return value is None or isinstance(value, (bool, int, float, str)) + + +def _properties(value: Any, where: str) -> dict[str, Any]: + """The properties of a node or a relationship to ingest: names that are identifiers, values + that are scalars or lists of scalars; ``key`` and ``source`` are the tool's.""" + if value is None: + return {} + if not isinstance(value, dict): + raise AppException(400, f"{where}.properties must be a map") + checked: dict[str, Any] = {} + for name, item in value.items(): + if not isinstance(name, str) or not PROPERTY_NAME.fullmatch(name): + raise AppException( + 400, f"{where}.properties has a name that is not an identifier: {name!r}" + ) + if name in ("key", "source"): + raise AppException(400, f"{where}.properties must not set {name} - the tool writes it") + if isinstance(item, list): + if not all(_scalar(element) and element is not None for element in item): + raise AppException(400, f"{where}.properties.{name} must be a list of scalars") + elif not _scalar(item): + raise AppException( + 400, f"{where}.properties.{name} must be a scalar or a list of scalars" + ) + if item is not None: + checked[name] = item + return checked + + +def _key(value: Any, where: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise AppException(400, f"{where} must be a non-empty string") + if len(value) > KEY_MAX_CHARS: + raise AppException(400, f"{where} is longer than {KEY_MAX_CHARS} characters") + return value + + +def _identifier(value: Any, where: str) -> str: + if not isinstance(value, str) or not IDENTIFIER.fullmatch(value): + raise AppException( + 400, + f"{where} must be an identifier - letters, digits and underscore, starting with a letter", + ) + return value + + +@dataclass(frozen=True) +class Ingest: + """A validated ingest: the nodes grouped by label and the relationships by type, each as the + rows a parameterized ``MERGE`` takes.""" + + nodes: dict[str, list[dict[str, Any]]] + relationships: dict[str, list[dict[str, Any]]] + source: str | None + node_count: int + relationship_count: int + + @property + def endpoint_keys(self) -> list[str]: + keys: list[str] = [] + for rows in self.relationships.values(): + for row in rows: + for key in (row["from"], row["to"]): + if key not in keys: + keys.append(key) + return keys + + +def plan_ingest(args: dict[str, Any], *, max_nodes: int) -> Ingest: + """Validate an ingest and group it: labels and types must be identifiers, keys non-empty + strings, properties scalars or lists of scalars, the counts inside the caps.""" + nodes = args.get("nodes") or [] + relationships = args.get("relationships") or [] + source = args.get("source") + if not isinstance(nodes, list) or not isinstance(relationships, list): + raise AppException(400, "nodes and relationships must be arrays") + if source is not None and not isinstance(source, str): + raise AppException(400, "source must be a string") + if not nodes and not relationships: + raise AppException(400, "nothing to ingest - give nodes, relationships or both") + if len(nodes) > max_nodes: + raise AppException( + 400, + f"{len(nodes)} nodes is over the limit of {max_nodes} per call ({GRAPH_INGEST_MAX_NODES}) - " + f"ingest in batches", + ) + if len(relationships) > max_nodes * INGEST_RELATIONSHIPS_PER_NODE: + raise AppException( + 400, + f"{len(relationships)} relationships is over the limit of " + f"{max_nodes * INGEST_RELATIONSHIPS_PER_NODE} per call - ingest in batches", + ) + by_label: dict[str, list[dict[str, Any]]] = {} + seen_keys: set[str] = set() + for index, node in enumerate(nodes): + where = f"nodes[{index}]" + if not isinstance(node, dict): + raise AppException(400, f"{where} must be a map") + unknown = sorted(str(k) for k in node if k not in ("key", "label", "properties")) + if unknown: + raise AppException( + 400, + f"{where} does not take {', '.join(unknown)} - a node has key, label and properties", + ) + key = _key(node.get("key"), f"{where}.key") + label = _identifier(node.get("label"), f"{where}.label") + if key in seen_keys: + raise AppException(400, f"{where}.key {key!r} appears twice in this call") + seen_keys.add(key) + by_label.setdefault(label, []).append( + {"key": key, "properties": _properties(node.get("properties"), where)} + ) + by_type: dict[str, list[dict[str, Any]]] = {} + for index, relationship in enumerate(relationships): + where = f"relationships[{index}]" + if not isinstance(relationship, dict): + raise AppException(400, f"{where} must be a map") + unknown = sorted( + str(k) for k in relationship if k not in ("from", "to", "type", "properties") + ) + if unknown: + raise AppException( + 400, + f"{where} does not take {', '.join(unknown)} - a relationship has from, to, type and " + f"properties", + ) + row = { + "from": _key(relationship.get("from"), f"{where}.from"), + "to": _key(relationship.get("to"), f"{where}.to"), + "properties": _properties(relationship.get("properties"), where), + } + by_type.setdefault(_identifier(relationship.get("type"), f"{where}.type"), []).append(row) + return Ingest(by_label, by_type, source, len(nodes), len(relationships)) + + +def ingest_statements(plan: Ingest) -> list[tuple[str, dict[str, Any]]]: + """The parameterized statements of an ingest, nodes first, then the relationships - one + ``UNWIND ... MERGE`` per label and per type, every value a parameter, ``source`` stamped.""" + stamp = ", n.source = $source" if plan.source is not None else "" + statements: list[tuple[str, dict[str, Any]]] = [] + for label, rows in plan.nodes.items(): + statements.append( + ( + f"UNWIND $rows AS row MERGE (n:`{label}` {{key: row.key}}) SET n += row.properties{stamp}", + {"rows": rows, "source": plan.source}, + ) + ) + stamp = ", r.source = $source" if plan.source is not None else "" + for kind, rows in plan.relationships.items(): + statements.append( + ( + ( + f"UNWIND $rows AS row MATCH (a {{key: row.from}}) MATCH (b {{key: row.to}}) " + f"MERGE (a)-[r:`{kind}`]->(b) SET r += row.properties{stamp}" + ), + {"rows": rows, "source": plan.source}, + ) + ) + return statements + + +ENDPOINTS_QUERY = ( + "UNWIND $keys AS key OPTIONAL MATCH (n {key: key}) WITH key, n WHERE n IS NULL RETURN key" +) + +# the schema procedures: Neo4j's, then Memgraph's under the same column names +NODE_PROPERTIES_QUERIES = ( + ( + "CALL db.schema.nodeTypeProperties() YIELD nodeLabels, propertyName, propertyTypes " + "RETURN nodeLabels, propertyName, propertyTypes" + ), + ( + "CALL schema.node_type_properties() YIELD nodeLabels, propertyName, propertyTypes " + "RETURN nodeLabels, propertyName, propertyTypes" + ), +) +RELATIONSHIP_PROPERTIES_QUERIES = ( + ( + "CALL db.schema.relTypeProperties() YIELD relType, propertyName, propertyTypes " + "RETURN relType, propertyName, propertyTypes" + ), + ( + "CALL schema.rel_type_properties() YIELD relType, propertyName, propertyTypes " + "RETURN relType, propertyName, propertyTypes" + ), +) +LABEL_COUNTS_QUERY = "MATCH (n) UNWIND labels(n) AS label RETURN label, count(*) AS count" +RELATIONSHIP_COUNTS_QUERY = "MATCH (a)-[r]->(b) RETURN type(r) AS type, labels(a) AS from, labels(b) AS to, count(*) AS count" + + +def _relationship_type_name(value: Any) -> str: + """``:`KNOWS``` as Neo4j's procedure spells a type, or ``:KNOWS``, to ``KNOWS``.""" + return str(value).lstrip(":").strip("`") + + +async def _first_available(tx: Transaction, queries: tuple[str, ...]) -> Rows: + """The rows of the first procedure the database knows; a procedure the database lacks is tried + as the next one, any other failure is raised.""" + failure: BaseException | None = None + for query in queries: + try: + return await tx.run(query) + except Exception as exc: # the driver's error tells a missing procedure from a failure + text = str(exc).lower() + code = str(getattr(exc, "code", "") or "") + missing = "ProcedureNotFound" in code or ( + "procedure" in text + and any( + hint in text + for hint in ( + "no procedure", + "not found", + "no such", + "unknown", + "exist", + "not registered", + ) + ) + ) + if missing: + failure = exc + continue + raise + assert failure is not None + raise failure + + +class GraphTools: + """The four knowledge-graph tools over one database: the schema, a read-only query, a write + and the structured ingest; the backend is the driver, or a fake in the tests.""" + + def __init__(self, sandbox: GraphSandbox, backend: Any | None = None): + self.sandbox = sandbox + self.backend: Any = backend if backend is not None else Bolt(sandbox) + + async def close(self) -> None: + close = getattr(self.backend, "close", None) + if close is not None: + await close() + + async def _run(self, work: Work, *, write: bool) -> Any: + try: + return await self.backend.execute(work, write=write) + except Exception as exc: # every failure becomes the tool's status, by type + error = graph_error(exc, timeout_ms=self.sandbox.timeout_ms) + if error.status >= 500 or error.status == 408: + log.warning("graph tool failed - %s (%d)", type(exc).__name__, error.status) + raise error from exc + + @staticmethod + def _parameters(args: dict[str, Any]) -> dict[str, Any]: + parameters = args.get("parameters") + if parameters is None: + return {} + if not isinstance(parameters, dict): + raise AppException(400, "parameters must be a map of names to values") + return {str(key): value for key, value in parameters.items()} + + async def schema(self, _headers: dict[str, str], body: Body) -> Any: + _arguments(body, GRAPH_SCHEMA_ROW) + + async def work(tx: Transaction) -> Any: + labels: dict[str, dict[str, Any]] = {} + for label, count in (await tx.run(LABEL_COUNTS_QUERY)).values: + labels[str(label)] = {"label": str(label), "count": int(count), "properties": []} + node_properties = await _first_available(tx, NODE_PROPERTIES_QUERIES) + for node_labels, name, types in node_properties.values: + for label in node_labels or []: + entry = labels.setdefault( + str(label), {"label": str(label), "count": 0, "properties": []} + ) + if name is not None: + entry["properties"].append( + {"name": str(name), "types": [str(t) for t in (types or [])]} + ) + kinds: dict[str, dict[str, Any]] = {} + for kind, from_labels, to_labels, count in ( + await tx.run(RELATIONSHIP_COUNTS_QUERY) + ).values: + entry = kinds.setdefault( + str(kind), + {"type": str(kind), "count": 0, "from": [], "to": [], "properties": []}, + ) + entry["count"] += int(count) + for label in from_labels or []: + if str(label) not in entry["from"]: + entry["from"].append(str(label)) + for label in to_labels or []: + if str(label) not in entry["to"]: + entry["to"].append(str(label)) + relationship_properties = await _first_available(tx, RELATIONSHIP_PROPERTIES_QUERIES) + for kind, name, types in relationship_properties.values: + entry = kinds.setdefault( + _relationship_type_name(kind), + { + "type": _relationship_type_name(kind), + "count": 0, + "from": [], + "to": [], + "properties": [], + }, + ) + if name is not None: + entry["properties"].append( + {"name": str(name), "types": [str(t) for t in (types or [])]} + ) + for entry in labels.values(): + entry["properties"].sort(key=lambda item: item["name"]) + for entry in kinds.values(): + entry["properties"].sort(key=lambda item: item["name"]) + entry["from"].sort() + entry["to"].sort() + return { + "labels": [labels[name] for name in sorted(labels)], + "relationship_types": [kinds[name] for name in sorted(kinds)], + } + + result = await self._run(work, write=False) + log.info( + "graph.schema 200 %d labels, %d relationship types", + len(result["labels"]), + len(result["relationship_types"]), + ) + return result + + async def query(self, _headers: dict[str, str], body: Body) -> Any: + args = _arguments(body, GRAPH_QUERY_ROW) + query = _string(args, "query").strip() + if not query: + raise AppException(400, "query must not be empty") + parameters = self._parameters(args) + clause = write_clause(query) + if clause is not None: + raise AppException( + 400, + f"query carries {clause}, a write clause - graph_query is read-only; " + f"graph_write or graph_ingest writes", + ) + limit = self.sandbox.max_rows + + async def work(tx: Transaction) -> Rows: + return await tx.run(query, parameters, limit=limit) + + rows: Rows = await self._run(work, write=False) + log.info("graph.query 200 %d rows%s", len(rows.values), " (cut)" if rows.truncated else "") + return { + "columns": rows.columns, + "rows": [[render_value(v) for v in row] for row in rows.values], + "truncated": rows.truncated, + } + + async def write(self, _headers: dict[str, str], body: Body) -> Any: + args = _arguments(body, GRAPH_WRITE_ROW) + query = _string(args, "query").strip() + if not query: + raise AppException(400, "query must not be empty") + parameters = self._parameters(args) + if not self.sandbox.delete: + clause = delete_clause(query) + if clause is not None: + raise AppException( + 400, + f"query carries {clause} - deletion is not allowed on this graph ({GRAPH_DELETE})", + ) + limit = self.sandbox.max_rows + + async def work(tx: Transaction) -> Rows: + return await tx.run(query, parameters, limit=limit) + + rows: Rows = await self._run(work, write=True) + counters = {name: int((rows.counters or {}).get(name, 0)) for name in COUNTER_NAMES} + log.info( + "graph.write 200 %s", + ", ".join(f"{k}={v}" for k, v in counters.items() if v) or "no change", + ) + return { + "counters": counters, + "columns": rows.columns, + "rows": [[render_value(v) for v in row] for row in rows.values], + "truncated": rows.truncated, + } + + async def ingest(self, _headers: dict[str, str], body: Body) -> Any: + args = _arguments(body, GRAPH_INGEST_ROW) + plan = plan_ingest(args, max_nodes=self.sandbox.ingest_max_nodes) + statements = ingest_statements(plan) + node_statements = len(plan.nodes) + endpoints = plan.endpoint_keys + + async def work(tx: Transaction) -> dict[str, int]: + for query, parameters in statements[:node_statements]: + await tx.run(query, parameters) + if endpoints: + missing = await tx.run(ENDPOINTS_QUERY, {"keys": endpoints}, limit=20) + if missing.values: + names = ", ".join(str(row[0]) for row in missing.values) + raise AppException( + 400, + f"relationship endpoints not found in the graph or in this call: {names}", + ) + for query, parameters in statements[node_statements:]: + await tx.run(query, parameters) + return {"nodes": plan.node_count, "relationships": plan.relationship_count} + + result = await self._run(work, write=True) + log.info( + "graph.ingest 200 %d nodes, %d relationships", result["nodes"], result["relationships"] + ) + return result + + # --- the clock ---------------------------------------------------------------------------------- @@ -1572,6 +2590,7 @@ def __init__(self, registry: FunctionRegistry | None = None): self.registry = registry or default_registry self.files: FileTools | None = None self.web: WebTools | None = None + self.graph: GraphTools | None = None self.registered: list[str] = [] def _register(self, route: str, handler: Any) -> None: @@ -1594,6 +2613,10 @@ async def boot(self) -> None: ("file.search", self.files.search), ): self._register(route, handler) + if documents_available(): + self._register("file.extract", self.files.extract) + else: + log.info("file.extract not registered - %s", DOCUMENTS_EXTRA) log.info("File tools registered - workspace %s", file_sandbox.root) web_sandbox = load_web_sandbox() if web_sandbox is None: @@ -1608,6 +2631,34 @@ async def boot(self) -> None: len(web_sandbox.rules), ", private addresses allowed" if web_sandbox.allow_private else "", ) + graph_sandbox = load_graph_sandbox() + if graph_sandbox is None: + log.info("Graph tools not registered - %s is not set", GRAPH_URI) + else: + self.graph = GraphTools(graph_sandbox) + self._register("graph.schema", self.graph.schema) + self._register("graph.query", self.graph.query) + if graph_sandbox.write: + self._register("graph.write", self.graph.write) + self._register("graph.ingest", self.graph.ingest) + else: + log.info( + "graph.write and graph.ingest not registered - %s is false", GRAPH_WRITE + ) + try: + await self.graph.backend.verify() + log.info( + "Graph tools registered - %s%s%s", + graph_sandbox.address, + ", writes allowed" if graph_sandbox.write else "", + ", deletion allowed" if graph_sandbox.delete else "", + ) + except Exception as exc: # noqa: BLE001 - logged, not fatal + log.warning( + "Graph tools registered - %s does not answer yet (%s); calls fail until it does", + graph_sandbox.address, + type(exc).__name__, + ) if _bool_setting(TIME_ENABLED, True): self._register("time.now", time_now) else: @@ -1621,6 +2672,8 @@ async def boot(self) -> None: async def shutdown(self) -> None: if self.web is not None: await self.web.close() + if self.graph is not None: + await self.graph.close() agent_tools = AgentTools() @@ -1639,6 +2692,7 @@ async def tools_health(headers: dict[str, str], _body: Body) -> Any: "tools": list(agent_tools.registered), "workspace": str(files.root) if files is not None else None, "allowed_sites": [str(rule) for rule in web.sandbox.rules] if web is not None else [], + "graph": agent_tools.graph.sandbox.address if agent_tools.graph is not None else None, } return "agent.tools is running fine" @@ -1675,9 +2729,28 @@ def _states() -> dict[str, str]: ) except ToolsError as exc: time_state = f"NOT registered ({exc})" + try: + graph = load_graph_sandbox() + if graph is None: + read_state = write_state = f"NOT registered ({GRAPH_URI} is not set)" + else: + read_state = f"registers ({graph.address})" + write_state = read_state if graph.write else f"NOT registered ({GRAPH_WRITE} is false)" + except ToolsError as exc: + read_state = write_state = f"NOT registered ({exc})" + extract_state = file_state + if file_state.startswith("registers") and not documents_available(): + extract_state = f"NOT registered ({DOCUMENTS_EXTRA})" for route in ROW_BY_ROUTE: group = route.split(".", 1)[0] - states[route] = {"file": file_state, "web": web_state, "time": time_state}[group] + if route == "file.extract": + states[route] = extract_state + elif route in ("graph.write", "graph.ingest"): + states[route] = write_state + elif group == "graph": + states[route] = read_state + else: + states[route] = {"file": file_state, "web": web_state, "time": time_state}[group] return states diff --git a/extensions/agent-tools/catalog/file_extract.json b/extensions/agent-tools/catalog/file_extract.json new file mode 100644 index 0000000..4a861da --- /dev/null +++ b/extensions/agent-tools/catalog/file_extract.json @@ -0,0 +1,27 @@ +{ + "name": "file_extract", + "description": "Extract the text of a PDF or Word document in the agent's workspace (an HTML or plain text file works too), with a marker before each page (--- page N ---). path is relative to the workspace root; pages selects a range such as 1-3,7 (default: all pages); the text is cut at max_chars. Returns the path, the document type, the number of pages the document has and the text. Use file_read for a plain text file.", + "input_schema": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "The document, relative to the workspace root." + }, + "pages": { + "type": "string", + "description": "The pages to extract, 1-based, such as 1-3,7; default: all." + }, + "max_chars": { + "type": "integer", + "minimum": 100, + "description": "Return at most this many characters (default and cap: the workspace's limit)." + } + }, + "required": [ + "path" + ], + "additionalProperties": false + }, + "route": "file.extract" +} diff --git a/extensions/agent-tools/catalog/graph_ingest.json b/extensions/agent-tools/catalog/graph_ingest.json new file mode 100644 index 0000000..26822f3 --- /dev/null +++ b/extensions/agent-tools/catalog/graph_ingest.json @@ -0,0 +1,74 @@ +{ + "name": "graph_ingest", + "description": "Load what you extracted from a document into the agent's knowledge graph, idempotently. Each node is merged on its key - unique across the graph, the label in lower case as its prefix (clause:12, party:supplier-a) - with its label and properties; each relationship is merged between two keys that exist (in this call or already in the graph) with its type and properties. Labels and types are identifiers (letters, digits and underscore, starting with a letter); property values are scalars or lists of scalars. Give source (the document's path or URL) so an answer can cite it. Running the same ingest twice changes nothing.", + "input_schema": { + "type": "object", + "properties": { + "nodes": { + "type": "array", + "description": "The entities: a key, a label and properties each.", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "Unique across the graph, prefixed with the label." + }, + "label": { + "type": "string", + "description": "The node's label, an identifier." + }, + "properties": { + "type": "object", + "description": "Scalar or list-of-scalar values by name." + } + }, + "required": [ + "key", + "label" + ], + "additionalProperties": false + } + }, + "relationships": { + "type": "array", + "description": "The relations: from a key to a key, with a type and properties.", + "items": { + "type": "object", + "properties": { + "from": { + "type": "string", + "description": "The key of the start node." + }, + "to": { + "type": "string", + "description": "The key of the end node." + }, + "type": { + "type": "string", + "description": "The relationship type, an identifier." + }, + "properties": { + "type": "object", + "description": "Scalar or list-of-scalar values by name." + } + }, + "required": [ + "from", + "to", + "type" + ], + "additionalProperties": false + } + }, + "source": { + "type": "string", + "description": "The document the facts come from - its path or URL." + } + }, + "required": [], + "additionalProperties": false + }, + "route": "graph.ingest", + "write": true +} diff --git a/extensions/agent-tools/catalog/graph_query.json b/extensions/agent-tools/catalog/graph_query.json new file mode 100644 index 0000000..5312d5c --- /dev/null +++ b/extensions/agent-tools/catalog/graph_query.json @@ -0,0 +1,22 @@ +{ + "name": "graph_query", + "description": "Run a read-only openCypher query against the agent's knowledge graph and return its rows. Pass values as parameters ($name in the query, the value under that name in parameters) instead of writing them into the query. A node comes back as {id, labels, properties}, a relationship as {id, type, start, end, properties}, a path as a list of them. Rows are capped: narrow the query with WHERE and LIMIT when the result was cut. A query that writes (CREATE, MERGE, SET, DELETE, REMOVE, DROP, LOAD CSV) is refused - use graph_write or graph_ingest.", + "input_schema": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The openCypher query, read-only, with $parameters." + }, + "parameters": { + "type": "object", + "description": "The values the query's $parameters take." + } + }, + "required": [ + "query" + ], + "additionalProperties": false + }, + "route": "graph.query" +} diff --git a/extensions/agent-tools/catalog/graph_schema.json b/extensions/agent-tools/catalog/graph_schema.json new file mode 100644 index 0000000..e83f014 --- /dev/null +++ b/extensions/agent-tools/catalog/graph_schema.json @@ -0,0 +1,11 @@ +{ + "name": "graph_schema", + "description": "The schema of the agent's knowledge graph: every node label with its count and its property names and types, and every relationship type with its count and the labels it connects. Read it before writing a query or an ingest, so labels, types and property names match what the graph holds.", + "input_schema": { + "type": "object", + "properties": {}, + "required": [], + "additionalProperties": false + }, + "route": "graph.schema" +} diff --git a/extensions/agent-tools/catalog/graph_write.json b/extensions/agent-tools/catalog/graph_write.json new file mode 100644 index 0000000..5c3b787 --- /dev/null +++ b/extensions/agent-tools/catalog/graph_write.json @@ -0,0 +1,23 @@ +{ + "name": "graph_write", + "description": "Run an openCypher statement that changes the agent's knowledge graph - an index or a constraint, a corrected property, a relationship between existing nodes - and return the counters of what changed. Pass every value as a parameter. DELETE and DROP are refused unless the deployment allows deletion. To load extracted entities and relations, prefer graph_ingest, which merges them idempotently.", + "input_schema": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "The openCypher statement, with $parameters." + }, + "parameters": { + "type": "object", + "description": "The values the statement's $parameters take." + } + }, + "required": [ + "query" + ], + "additionalProperties": false + }, + "route": "graph.write", + "write": true +} diff --git a/extensions/agent-tools/dev/graph-down.sh b/extensions/agent-tools/dev/graph-down.sh new file mode 100755 index 0000000..c4c6625 --- /dev/null +++ b/extensions/agent-tools/dev/graph-down.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# Stop and remove the development Neo4j (the graph goes with the container). +set -uo pipefail +docker rm -f mercury-graph 2>/dev/null || true +echo "removed mercury-graph" diff --git a/extensions/agent-tools/dev/graph-up.sh b/extensions/agent-tools/dev/graph-up.sh new file mode 100755 index 0000000..0e2b8d7 --- /dev/null +++ b/extensions/agent-tools/dev/graph-up.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# The agent's knowledge graph for development (RFC-0013, ruling R11): Neo4j Community on Colima (or +# Docker Desktop), with its own Browser as the viewer. The password comes from the environment and +# is never written to a file. +# +# GRAPH_PASSWORD=... extensions/agent-tools/dev/graph-up.sh +# +# Then run the tools with the graph on, in the same shell: resources/application.yml reads the user +# from GRAPH_USER (default neo4j) and the password from GRAPH_PASSWORD, and the other keys default to +# this container (bolt://127.0.0.1:7687, the default database): +# +# mercury-serve extensions/agent-tools/agent_tools.py -Dtools.graph.uri=bolt://127.0.0.1:7687 \ +# -Dtools.graph.write=true +# +# and browse the graph at http://127.0.0.1:7474 (user neo4j, the same password). Neo4j needs a +# password of at least eight characters. The container keeps its data until graph-down.sh removes it. +set -euo pipefail +: "${GRAPH_PASSWORD:?set GRAPH_PASSWORD in the environment - never in a file}" + +docker run -d --name mercury-graph -p 7474:7474 -p 7687:7687 \ + -e NEO4J_AUTH="neo4j/${GRAPH_PASSWORD}" \ + neo4j:5-community + +echo "Neo4j: bolt://127.0.0.1:7687, user neo4j (ready in about twenty seconds)" +echo "Browser: http://127.0.0.1:7474" diff --git a/extensions/agent-tools/resources/application.yml b/extensions/agent-tools/resources/application.yml index 9378d9c..259cd79 100644 --- a/extensions/agent-tools/resources/application.yml +++ b/extensions/agent-tools/resources/application.yml @@ -20,7 +20,7 @@ mandatory.health.dependencies: 'tools.health' # Opt-in lists for the /env endpoint - nothing is ever dumped wholesale. show.env.variables: 'LOG_LEVEL' -show.application.properties: 'application.name, rest.server.port, tools.file.root, tools.web.allow, tools.time' +show.application.properties: 'application.name, rest.server.port, tools.file.root, tools.web.allow, tools.graph.uri, tools.graph.write, tools.time' # --- the sandboxes: a tool whose sandbox is not configured does not register ------------------ # @@ -37,6 +37,9 @@ tools.file.hidden: false tools.file.write.extensions: '' # a line file.search returns is cut to this many characters tools.file.line.max.chars: 500 +# the most characters file.extract returns of a document (PDF and Word need the documents extra: +# pip install 'mercury-composable[documents]'; without it file.extract does not register) +tools.file.extract.max.chars: 60000 # The web: the sites the web tools (web.fetch, web.crawl) may reach - comma-separated host # patterns, e.g. 'docs.example.com, *.example.org'. A host is reached over https unless it is @@ -55,6 +58,23 @@ tools.web.crawl.max.pages: 50 tools.web.crawl.delay.ms: 500 tools.web.page.max.chars: 20000 +# The knowledge graph: the one database the graph tools reach over the Bolt protocol (Neo4j, +# Memgraph; pip install 'mercury-composable[graph]'). graph.schema and graph.query register when the +# URI is set; graph.write and graph.ingest only when tools.graph.write is true; DELETE and DROP are +# refused unless tools.graph.delete is true as well. The credential is a reference, resolved from the +# environment and never logged. Unset, the graph tools do not register. +tools.graph.uri: '${TOOLS_GRAPH_URI:}' +tools.graph.database: '' +tools.graph.username: '${GRAPH_USER:neo4j}' +tools.graph.password: '${GRAPH_PASSWORD:}' +tools.graph.write: false +tools.graph.delete: false +# the most rows graph.query and graph.write return (the tool's cap is 2000), how long one +# transaction may take (set server-side), and the most nodes one graph.ingest call may carry +tools.graph.max.rows: 200 +tools.graph.timeout.ms: 10000 +tools.graph.ingest.max.nodes: 500 + # The clock (time.now) reads nothing and registers unless false. tools.time: true diff --git a/memory/continuity.md b/memory/continuity.md index aa0ef42..d009396 100644 --- a/memory/continuity.md +++ b/memory/continuity.md @@ -53,7 +53,9 @@ optional extras, all for the LLM helper (`extensions/llm-helper`; the package itself stays SDK-free): `llm` = `anthropic` >=1,<2 (`pip install 'mercury-composable[llm]'`; `google-genai` was removed 2026-10-01 with the Gemini provider, PR #38), `bedrock` = `anthropic[bedrock]` >=1,<2 (the AWS Bedrock backend, PR #43), `redis` = `redis` >=5,<9 (the transcript - store, PR #47), `postgres` = `psycopg[binary,pool]` >=3.2,<4 (the transcript audit store, 2026-11-17) + store, PR #47), `postgres` = `psycopg[binary,pool]` >=3.2,<4 (the transcript audit store, 2026-11-17), and for the + built-in agent tools (`extensions/agent-tools`): `graph` = `neo4j` >=6,<7 (the knowledge-graph tools over Bolt) and + `documents` = `pypdf` >=6,<7 + `python-docx` >=1.1,<2 (`file.extract`), both 2026-11-17 ## Architectural Invariants diff --git a/memory/open-threads/thread-bp-agent-tools-python.md b/memory/open-threads/thread-bp-agent-tools-python.md index 15f0cc7..540efa1 100644 --- a/memory/open-threads/thread-bp-agent-tools-python.md +++ b/memory/open-threads/thread-bp-agent-tools-python.md @@ -1,12 +1,17 @@ - [ ] **(blueprint) The essential built-in tools for agent loops, RFC-0013 build plan step 1 and 2 here, Python first (Eric: "proceed with essential tools", 2026-11-17; the spec is mercury-composable - `draft-design-specs/agent-essential-tools.md`, settled, rulings R1-R16).** **Step 1 BUILT 2026-11-17** as PR #63 (squash `55db6f4`, MERGED 2026-11-17): + `draft-design-specs/agent-essential-tools.md`, settled, rulings R1-R16).** **Step 1 BUILT 2026-11-17** as PR #63 (merge `55db6f4`, MERGED 2026-11-17): `extensions/agent-tools/agent_tools.py`, the seven routes, the catalog files, `describe`, `tools.health`, README, 98 tests on a workspace and a fixture site, a live https fetch through the pinned-address path; six defaults set without a ruling are listed in the session log (hidden entries invisible to every file tool, the resolved address pinned, a write bounded by `tools.file.max.bytes`, no `strict` on the rows, the statuses, row names = routes with `_`). In passing: the MCP binding's direct run never attached its boot hook (fixed; the Node binding attaches its - hooks on both paths - checked 2026-11-17, nothing to do there). Next: the engines' docs page, then step 2. The plan as settled - step 1: `extensions/agent-tools/agent_tools.py` (the layout of `extensions/mcp-binding`: a module docstring, a + hooks on both paths - checked 2026-11-17, nothing to do there). The engines' page `docs/guides/agent-tools.md` + landed as mercury-composable #644. **Step 2 BUILT 2026-11-17** (PR + opened the same day): the four graph tools over the Bolt driver (`graph` extra; a `Transaction` seam, a fake for the + tests, Neo4j and Memgraph schema procedures), `file.extract` behind the `documents` extra, `dev/graph-up.sh` / + `graph-down.sh`, 161 tests and a live round trip on the development Neo4j; eight defaults set without a ruling in + the session log. Next: the engines' page and spec for step 2, then the Node twin. The plan as settled - step 1: `extensions/agent-tools/agent_tools.py` (the layout of `extensions/mcp-binding`: a module docstring, a `README.md`, `resources/application.yml`, a `describe` command printing every catalog row, `platform.on_startup` for the gated registration) with the file tools inside `tools.file.root` (`file.read`, `file.write` marked `write: true` with `create` the default, `file.list`, `file.search`; paths resolved with symlinks followed and refused outside the root; diff --git a/memory/sessions/2026-11-17-101635.md b/memory/sessions/2026-11-17-101635.md index 223dcf8..7819047 100644 --- a/memory/sessions/2026-11-17-101635.md +++ b/memory/sessions/2026-11-17-101635.md @@ -48,7 +48,7 @@ existing file under `create`, 502 an unresolvable host or a failed connection. 6. **Row names are the routes with `_` for `.`** (`file_read` for `file.read`), pinned by a test. -Opened as PR #63; **MERGED 2026-11-17** (squash `55db6f4`). Next: the engines' documentation page "Built-in Agent Tools" (mercury-composable, with the skill inventory, the nav +Opened as PR #63; **MERGED 2026-11-17** (merge `55db6f4`). Next: the engines' documentation page "Built-in Agent Tools" (mercury-composable, with the skill inventory, the nav and `llms.txt`), then step 2 here (the graph tools, `file.extract`), then the Node twin. ## Memory References diff --git a/memory/sessions/2026-11-17-104217.md b/memory/sessions/2026-11-17-104217.md new file mode 100644 index 0000000..eea057e --- /dev/null +++ b/memory/sessions/2026-11-17-104217.md @@ -0,0 +1,60 @@ +# Session (2026-11-17T10:42:17.000Z) + +**Agent:** Claude Code +**Title:** RFC-0013 build plan step 2 - the knowledge-graph tools over Bolt and file.extract, driven live on Neo4j +**User:** Eric - "PR 63 merged", "PR 644 merged" (both recorded on main); the standing direction "proceed with essential tools" + +## What We Did + +- Recorded #63 (this repo) and mercury-composable #644 as merged on their `main` branches. +- **The four knowledge-graph tools** in `extensions/agent-tools/agent_tools.py`: `GraphSandbox` from `tools.graph.*` + (a Bolt URI, the database, the credential by reference, the write and delete gates, the row cap, the timeout, the + ingest cap); `Bolt`, the official driver's async pool with every statement inside a managed transaction and the + timeout set server-side through `unit_of_work`; a `Transaction` seam the tests' fake implements. `graph.schema` + merges two counting queries with the database's property procedures (Neo4j's `db.schema.*`, Memgraph's `schema.*` + by fallback when the first is a missing procedure); `graph.query` refuses a write clause outside a string or a + comment before sending, runs in a read transaction and renders nodes, relationships, paths, temporal and spatial + values for the model; `graph.write` returns the counters (and any rows); `graph.ingest` validates and groups a + model's extraction, one parameterized `UNWIND ... MERGE` per label and per type, and checks the relationship + endpoints inside the transaction - a missing key is a 400 naming it and nothing is written. The driver's exceptions map + to 400 by the database's own code, 408, 503 (credential, unreachable - logged by type only) and 502. +- **`file.extract`** (PDF through pypdf, Word through python-docx, HTML through the in-house reader, text) with + `--- page N ---` markers, a page range and `tools.file.extract.max.chars`; registers with the file tools only when + the `documents` extra is installed. Extras `graph` and `documents` in `pyproject.toml` (dev installs both). +- `dev/graph-up.sh` / `graph-down.sh` (Neo4j 5 Community on Colima, its Browser the viewer); the five new catalog + files; `describe` states for the graph gates and the documents extra; `tools.health` reports the graph's address. +- **Tests:** 161 in `tests/test_agent_tools.py` - the pure half (the clause scan, rendering with the driver's own + classes, the ingest plan and statements, the error mapping on exceptions the driver's factory builds), the tools over + a fake backend (the schema from both procedure families, the row cap, the delete gate, the ingest's statement order + and endpoint check), `file.extract` on a PDF and a Word document generated in the test, the boot gates, and a + **live round trip on the development Neo4j** (ingest twice = one node, a query rendering node, relationship and path, + the schema with counts, a syntax error by code, a missing endpoint, the delete gate): PASSED. Whole suite 598 passed; + one pre-existing timing test of the MCP binding fails under full-suite load and passes alone (3 of 3). +- README, `resources/application.yml`, CHANGELOG (Added 3), the stack fact's extras updated. + +## Defaults set without a ruling (for the spec's build notes, section 14) + +1. A relationship whose endpoint does not exist fails the whole ingest with a 400 naming the key - checked inside the + transaction after the node merges, so nothing is half-written; never a silent skip. +2. Rows are capped by configuration only (`tools.graph.max.rows`, 200, the tool's cap 2000); the model narrows with + `WHERE` and `LIMIT`. +3. An ingest call carries at most `tools.graph.ingest.max.nodes` nodes and four times as many relationships; a key is at + most 512 characters; property names are identifiers; `key` and `source` are the tool's; a null value is dropped. +4. `graph.write` returns `columns`, `rows` and `truncated` beside `counters`, so a `RETURN` after a write is kept. +5. A label the property procedure lists with no instance, or a type with no property, still appears with count 0. +6. The rendering: a node `{id, labels (sorted), properties}`, a relationship `{id, type, start, end, properties}`, a path + the alternating list, temporal values `iso_format`, a point `{srid, coordinates}`, bytes base64. +7. A database that does not answer at boot is logged and its tools answer 503 until it does (the audit store's + precedent, [[transcript-audit-store-python]]); a URI that is not Bolt, or set without the driver, stops the boot. +8. `file.extract` returns `type` (`pdf`, `docx`, `html`, `text`) and the document's page count; a Word document is one + page; `tools.file.extract.max.chars` (60 000) is the cap key the paper did not name. + +Next: the engines' page and the spec's section 14 for step 2, then the Node twin (step 3; check its MCP binding's +direct-run hook too), the Playground graphs and the recipes (steps 4-5). + +## Memory References + +- Referenced: bp-agent-tools-python (edited: step 2 BUILT), transcript-audit-store-python (the boot precedent), + stack-deps-aiohttp-msgpack (edited: the graph and documents extras), conv-python-quality-gates (the gates run) +- Created: (none) +- Superseded: (none) diff --git a/pyproject.toml b/pyproject.toml index e39580e..c24cd1c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,6 +52,12 @@ postgres = ["psycopg[binary,pool]>=3.2,<4"] # the MCP binding (extensions/mcp-binding) - the official MCP SDK's client, one route per # allowlisted remote tool; the package itself stays SDK-free mcp = ["mcp>=2,<3"] +# the knowledge-graph tools of the agent tools (extensions/agent-tools, tools.graph.uri) - the +# official Bolt driver, asynchronous, reaching Neo4j and Memgraph alike; the file, web and clock +# tools need no extra +graph = ["neo4j>=6,<7"] +# file.extract of the agent tools - PDF and Word documents to text; without it the tool does not register +documents = ["pypdf>=6,<7", "python-docx>=1.1,<2"] dev = [ "pytest>=8", "pytest-asyncio>=0.23", @@ -60,6 +66,9 @@ dev = [ "redis>=5,<9", "psycopg[binary,pool]>=3.2,<4", "mcp>=2,<3", + "neo4j>=6,<7", + "pypdf>=6,<7", + "python-docx>=1.1,<2", # the store's compare-and-set is a Lua script; the [lua] extra runs it in the fake "fakeredis[lua]>=2.26", ] diff --git a/tests/test_agent_tools.py b/tests/test_agent_tools.py index 925a29f..cf24414 100644 --- a/tests/test_agent_tools.py +++ b/tests/test_agent_tools.py @@ -14,12 +14,14 @@ import asyncio import importlib.util +import io import json import logging import os import re import sys from collections.abc import AsyncIterator, Callable, Iterator +from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -47,10 +49,17 @@ "file.write", "file.list", "file.search", + "file.extract", "web.fetch", "web.crawl", + "graph.schema", + "graph.query", + "graph.write", + "graph.ingest", "time.now", ) +STEP_ONE_ROUTES = tuple(r for r in ROUTES if not r.startswith("graph.")) +WRITERS = {"file_write", "graph_write", "graph_ingest"} # the loop's closed schema subset (ToolSchema in the engines' agent loop), as the rows may use it SCHEMA_KEYWORDS = { @@ -956,8 +965,8 @@ async def test_a_full_configuration_registers_every_tool_and_serves_them_through with caplog.at_level(logging.WARNING): await app.boot() assert "tools.web.crawl.max.pages=80 is over the tool's cap 50" in caplog.text - assert app.registered == list(ROUTES) - for route in ROUTES: + assert app.registered == list(STEP_ONE_ROUTES) + for route in STEP_ONE_ROUTES: service = registry.get(route) assert service is not None and not service.private and service.instances == 10, route po = PostOffice(registry=registry) @@ -972,7 +981,8 @@ async def test_a_full_configuration_registers_every_tool_and_serves_them_through assert clock.get_status() == 200 and clock.body["timezone"] == "UTC" info = await tools.tools_health({"type": "info"}, None) assert info["service"] == "agent.tools" - assert info["tools"] == list(ROUTES) + assert info["tools"] == list(STEP_ONE_ROUTES) + assert info["graph"] is None assert info["workspace"] == str(workspace.resolve()) assert info["allowed_sites"] == ["http://127.0.0.1"] assert await tools.tools_health({"type": "health"}, None) == "agent.tools is running fine" @@ -1006,7 +1016,9 @@ def test_describe_prints_every_row_and_what_registers( ) -> None: assert tools.describe([]) == 0 out = capsys.readouterr().out - assert out.startswith("# 7 built-in tool(s)") + assert out.startswith("# 12 built-in tool(s)") + assert "## graph.schema (graph_schema) - NOT registered (tools.graph.uri is not set)" in out + assert "## file.extract (file_extract) - NOT registered (tools.file.root is not set)" in out assert "## file.read (file_read) - NOT registered (tools.file.root is not set)" in out assert "## web.fetch (web_fetch) - NOT registered (tools.web.allow is empty)" in out assert "## time.now (time_now) - registers" in out @@ -1047,9 +1059,954 @@ def test_the_rows_satisfy_the_loops_catalog_rules(row: dict[str, Any]) -> None: schema = row["input_schema"] assert schema["type"] == "object" and schema["additionalProperties"] is False assert set(schema["required"]) <= set(schema["properties"]) - for name, prop in schema["properties"].items(): - assert set(prop) <= SCHEMA_KEYWORDS, (name, set(prop) - SCHEMA_KEYWORDS) - assert prop["type"] in ("string", "integer", "boolean") - assert row.get("write", False) is (row["name"] == "file_write"), ( - "file_write is the one writer of step 1" + _check_schema(schema) + assert row.get("write", False) is (row["name"] in WRITERS), ( + "the writers carry the mark, nothing else" ) + + +def _check_schema(schema: dict[str, Any]) -> None: + """Every keyword in the loop's closed subset, every type a JSON type, objects and arrays checked + through.""" + assert set(schema) <= SCHEMA_KEYWORDS, set(schema) - SCHEMA_KEYWORDS + assert schema["type"] in ("string", "integer", "boolean", "object", "array") + if schema["type"] == "object": + for prop in schema.get("properties", {}).values(): + _check_schema(prop) + assert set(schema.get("required", [])) <= set(schema.get("properties", {})) + if schema["type"] == "array": + _check_schema(schema["items"]) + + +# --- the knowledge graph: the pure half --------------------------------------------------------- + + +@pytest.mark.parametrize( + ("query", "clause"), + [ + ("MATCH (n) RETURN n", None), + ("MATCH (n) WHERE n.name = 'please SET this' RETURN n", None), + ("MATCH (n:`CREATE`) RETURN n.offset, n.settings // DELETE later", None), + ("MATCH (n) RETURN n /* MERGE */", None), + ("CREATE (n:X) RETURN n", "CREATE"), + ("match (n) set n.x = 1", "SET"), + ("MATCH (n) DETACH DELETE n", "DELETE"), + ("MERGE (n:X {k: 1})", "MERGE"), + ("MATCH (n) REMOVE n:X", "REMOVE"), + ("DROP INDEX x", "DROP"), + ("LOAD CSV FROM 'file:///x.csv' AS row RETURN row", "LOAD CSV"), + ], +) +def test_write_clauses_are_found_outside_literals_and_comments( + query: str, clause: str | None +) -> None: + assert tools.write_clause(query) == clause + + +def test_delete_clauses() -> None: + assert tools.delete_clause("MATCH (n) DETACH DELETE n") == "DELETE" + assert tools.delete_clause("DROP CONSTRAINT c") == "DROP" + assert tools.delete_clause("MERGE (n:X) SET n.deleted = 'DELETE'") is None + assert tools.delete_clause("CREATE INDEX i FOR (n:X) ON (n.key)") is None + + +@dataclass +class FakeNode: + element_id: str + labels: frozenset[str] + props: dict[str, Any] + + def items(self) -> Any: + return self.props.items() + + +@dataclass +class FakeRelationship: + element_id: str + type: str + start_node: FakeNode + end_node: FakeNode + props: dict[str, Any] + + def items(self) -> Any: + return self.props.items() + + +@dataclass +class FakePath: + nodes: list[FakeNode] + relationships: list[FakeRelationship] + + +def test_render_value_shapes_nodes_relationships_paths_and_driver_types() -> None: + import neo4j.graph + import neo4j.spatial + import neo4j.time + + a = FakeNode("4:g:1", frozenset({"Party", "Clause"}), {"key": "clause:1", "n": 1}) + b = FakeNode("4:g:2", frozenset({"Party"}), {"key": "party:a"}) + r = FakeRelationship("5:g:9", "BINDS", a, b, {"since": 2026}) + assert tools.render_value(a) == { + "id": "4:g:1", + "labels": ["Clause", "Party"], + "properties": {"key": "clause:1", "n": 1}, + } + assert tools.render_value(r) == { + "id": "5:g:9", + "type": "BINDS", + "start": "4:g:1", + "end": "4:g:2", + "properties": {"since": 2026}, + } + rendered_path = tools.render_value(FakePath([a, b], [r])) + assert [item.get("id") for item in rendered_path] == ["4:g:1", "5:g:9", "4:g:2"] + # the driver's own node class renders the same way + real = neo4j.graph.Node(neo4j.graph.Graph(), "4:real:7", 7, ["Clause"], {"key": "clause:7"}) + assert tools.render_value(real) == { + "id": "4:real:7", + "labels": ["Clause"], + "properties": {"key": "clause:7"}, + } + assert ( + tools.render_value(neo4j.time.DateTime(2026, 11, 17, 10, 0, 0)) + == "2026-11-17T10:00:00.000000000" + ) + assert tools.render_value(neo4j.time.Date(2026, 11, 17)) == "2026-11-17" + assert tools.render_value(neo4j.spatial.CartesianPoint((1.0, 2.0))) == { + "srid": 7203, + "coordinates": [1.0, 2.0], + } + assert tools.render_value(b"\x00\x01") == "AAE=" + assert tools.render_value({"k": [1, "a", None, True]}) == {"k": [1, "a", None, True]} + assert tools.render_value(3.5) == 3.5 + + +def test_graph_errors_map_to_statuses_by_type() -> None: + import neo4j.exceptions as errors + + def hydrate(code: str, message: str) -> BaseException: + return errors.Neo4jError._hydrate_neo4j( + code=code, message=message + ) # the driver's own factory + + syntax = tools.graph_error( + hydrate("Neo.ClientError.Statement.SyntaxError", "Invalid input 'X'"), timeout_ms=10 + ) + assert (syntax.status, syntax.message) == ( + 400, + "Neo.ClientError.Statement.SyntaxError: Invalid input 'X'", + ) + timed = tools.graph_error( + hydrate("Neo.ClientError.Transaction.TransactionTimedOut", "took too long"), timeout_ms=10 + ) + assert timed.status == 408 and "within 10 ms" in timed.message + auth = tools.graph_error( + hydrate("Neo.ClientError.Security.Unauthorized", "the credential itself"), timeout_ms=10 + ) + assert auth.status == 503 and "the credential itself" not in auth.message + transient = tools.graph_error( + hydrate("Neo.TransientError.Transaction.DeadlockDetected", "deadlock"), timeout_ms=10 + ) + assert transient.status == 503 + unavailable = tools.graph_error(errors.ServiceUnavailable("gone"), timeout_ms=10) + assert (unavailable.status, unavailable.message) == ( + 503, + "the graph database is not reachable (ServiceUnavailable)", + ) + assert tools.graph_error(asyncio.TimeoutError(), timeout_ms=10).status == 408 + assert tools.graph_error(RuntimeError("x"), timeout_ms=10).status == 502 + passthrough = AppException(400, "mine") + assert tools.graph_error(passthrough, timeout_ms=10) is passthrough + + +def test_plan_ingest_groups_and_validates() -> None: + plan = tools.plan_ingest( + { + "nodes": [ + { + "key": "clause:1", + "label": "Clause", + "properties": {"text": "a", "n": 1, "tags": ["x", "y"], "gone": None}, + }, + {"key": "party:a", "label": "Party"}, + {"key": "clause:2", "label": "Clause", "properties": {}}, + ], + "relationships": [ + { + "from": "clause:1", + "to": "party:a", + "type": "BINDS", + "properties": {"since": 2026}, + } + ], + "source": "docs/a.md", + }, + max_nodes=10, + ) + assert list(plan.nodes) == ["Clause", "Party"] + assert plan.nodes["Clause"] == [ + {"key": "clause:1", "properties": {"text": "a", "n": 1, "tags": ["x", "y"]}}, + {"key": "clause:2", "properties": {}}, + ] + assert plan.relationships == { + "BINDS": [{"from": "clause:1", "to": "party:a", "properties": {"since": 2026}}] + } + assert (plan.node_count, plan.relationship_count, plan.source) == (3, 1, "docs/a.md") + assert plan.endpoint_keys == ["clause:1", "party:a"] + statements = tools.ingest_statements(plan) + assert [q for q, _ in statements] == [ + "UNWIND $rows AS row MERGE (n:`Clause` {key: row.key}) SET n += row.properties, n.source = $source", + "UNWIND $rows AS row MERGE (n:`Party` {key: row.key}) SET n += row.properties, n.source = $source", + ( + "UNWIND $rows AS row MATCH (a {key: row.from}) MATCH (b {key: row.to}) MERGE (a)-[r:`BINDS`]->(b) " + "SET r += row.properties, r.source = $source" + ), + ] + assert statements[0][1] == {"rows": plan.nodes["Clause"], "source": "docs/a.md"} + without_source = tools.ingest_statements( + tools.plan_ingest({"nodes": [{"key": "k", "label": "L"}]}, max_nodes=10) + ) + assert without_source[0][0].endswith("SET n += row.properties") + + +@pytest.mark.parametrize( + ("args", "message"), + [ + ({}, "nothing to ingest"), + ({"nodes": "x"}, "must be arrays"), + ({"nodes": [{"key": "k", "label": "Bad Label"}]}, "nodes[0].label must be an identifier"), + ({"nodes": [{"key": "k", "label": "9L"}]}, "nodes[0].label must be an identifier"), + ({"nodes": [{"key": "", "label": "L"}]}, "nodes[0].key must be a non-empty string"), + ({"nodes": [{"key": "k", "label": "L"}, {"key": "k", "label": "L"}]}, "appears twice"), + ( + {"nodes": [{"key": "k", "label": "L", "properties": {"bad-name": 1}}]}, + "not an identifier", + ), + ({"nodes": [{"key": "k", "label": "L", "properties": {"key": "x"}}]}, "must not set key"), + ( + {"nodes": [{"key": "k", "label": "L", "properties": {"nested": {"a": 1}}}]}, + "scalar or a list of scalars", + ), + ( + {"nodes": [{"key": "k", "label": "L", "properties": {"mixed": [1, {"a": 1}]}}]}, + "list of scalars", + ), + ({"nodes": [{"key": "k", "label": "L", "extra": 1}]}, "nodes[0] does not take extra"), + ( + {"relationships": [{"from": "a", "to": "b", "type": "has space"}]}, + "relationships[0].type must be an identifier", + ), + ( + {"relationships": [{"from": "a", "to": "b"}]}, + "relationships[0].type must be an identifier", + ), + ({"nodes": [{"key": "k", "label": "L"}], "source": 3}, "source must be a string"), + ( + {"nodes": [{"key": f"k{i}", "label": "L"} for i in range(3)]}, + "3 nodes is over the limit of 2", + ), + ( + {"relationships": [{"from": "a", "to": "b", "type": "T"} for _ in range(9)]}, + "9 relationships is over the limit of 8", + ), + ], +) +def test_plan_ingest_refuses_by_rule(args: dict[str, Any], message: str) -> None: + status, text = _status(lambda: tools.plan_ingest(args, max_nodes=2)) + assert status == 400 + assert message in text, text + + +# --- the knowledge graph: the tools over a fake backend ---------------------------------------- + + +class FakeTransaction(tools.Transaction): + def __init__(self, script: Callable[[str, dict[str, Any], int | None], Any]): + self.script = script + self.calls: list[tuple[str, dict[str, Any], int | None]] = [] + + async def run( + self, query: str, parameters: dict[str, Any] | None = None, *, limit: int | None = None + ) -> Any: + self.calls.append((query, parameters or {}, limit)) + return self.script(query, parameters or {}, limit) + + +class FakeBackend: + """Runs the work of a transaction against a script: (query, parameters, limit) -> Rows, or raise.""" + + def __init__(self, script: Callable[[str, dict[str, Any], int | None], Any]): + self.script = script + self.transactions: list[FakeTransaction] = [] + self.modes: list[bool] = [] + self.closed = False + + async def verify(self) -> None: + return None + + async def close(self) -> None: + self.closed = True + + async def execute(self, work: Any, *, write: bool) -> Any: + tx = FakeTransaction(self.script) + self.transactions.append(tx) + self.modes.append(write) + return await work(tx) + + @property + def calls(self) -> list[tuple[str, dict[str, Any], int | None]]: + return [call for tx in self.transactions for call in tx.calls] + + +def _rows( + columns: list[str], + values: list[list[Any]], + *, + truncated: bool = False, + counters: dict[str, int] | None = None, +) -> Any: + return tools.Rows(columns, values, truncated, counters) + + +def _graph( + script: Callable[[str, dict[str, Any], int | None], Any], **settings: Any +) -> tuple[Any, FakeBackend]: + sandbox = tools.GraphSandbox(uri="bolt://graph.example:7687", **settings) + backend = FakeBackend(script) + return tools.GraphTools(sandbox, backend=backend), backend + + +def _schema_script(*, memgraph: bool = False) -> Callable[[str, dict[str, Any], int | None], Any]: + def script(query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: + if query == tools.LABEL_COUNTS_QUERY: + return _rows(["label", "count"], [["Clause", 12], ["Party", 3]]) + if query == tools.RELATIONSHIP_COUNTS_QUERY: + return _rows( + ["type", "from", "to", "count"], + [["BINDS", ["Clause"], ["Party"], 7], ["BINDS", ["Rule"], ["Party"], 1]], + ) + if query == tools.NODE_PROPERTIES_QUERIES[0]: + if memgraph: + raise RuntimeError("There is no procedure named 'db.schema.nodeTypeProperties'.") + return _rows( + ["nodeLabels", "propertyName", "propertyTypes"], + [ + [["Clause"], "text", ["String"]], + [["Clause"], "key", ["String"]], + [["Party"], "key", ["String"]], + [["Orphan"], None, None], + ], + ) + if query == tools.NODE_PROPERTIES_QUERIES[1]: + assert memgraph, "the fallback runs only when the first procedure is missing" + return _rows( + ["nodeLabels", "propertyName", "propertyTypes"], [[["Clause"], "key", ["String"]]] + ) + if query == tools.RELATIONSHIP_PROPERTIES_QUERIES[0]: + if memgraph: + raise RuntimeError("There is no procedure named 'db.schema.relTypeProperties'.") + return _rows( + ["relType", "propertyName", "propertyTypes"], + [[":`BINDS`", "source", ["String"]], [":`CITES`", None, None]], + ) + if query == tools.RELATIONSHIP_PROPERTIES_QUERIES[1]: + return _rows( + ["relType", "propertyName", "propertyTypes"], [[":BINDS", "source", ["String"]]] + ) + raise AssertionError(f"unexpected query {query}") + + return script + + +@pytest.mark.asyncio +async def test_graph_schema_merges_counts_and_properties() -> None: + graph, backend = _graph(_schema_script()) + schema = await graph.schema({}, None) + assert schema["labels"] == [ + { + "label": "Clause", + "count": 12, + "properties": [ + {"name": "key", "types": ["String"]}, + {"name": "text", "types": ["String"]}, + ], + }, + {"label": "Orphan", "count": 0, "properties": []}, + {"label": "Party", "count": 3, "properties": [{"name": "key", "types": ["String"]}]}, + ] + assert schema["relationship_types"] == [ + { + "type": "BINDS", + "count": 8, + "from": ["Clause", "Rule"], + "to": ["Party"], + "properties": [{"name": "source", "types": ["String"]}], + }, + {"type": "CITES", "count": 0, "from": [], "to": [], "properties": []}, + ] + assert backend.modes == [False], "the schema is read in one read transaction" + + +@pytest.mark.asyncio +async def test_graph_schema_falls_back_to_memgraphs_procedures() -> None: + graph, backend = _graph(_schema_script(memgraph=True)) + schema = await graph.schema({}, {}) + assert [label["label"] for label in schema["labels"]] == ["Clause", "Party"] + assert schema["relationship_types"][0]["properties"] == [ + {"name": "source", "types": ["String"]} + ] + queries = [call[0] for call in backend.calls] + assert ( + tools.NODE_PROPERTIES_QUERIES[1] in queries + and tools.RELATIONSHIP_PROPERTIES_QUERIES[1] in queries + ) + + +@pytest.mark.asyncio +async def test_graph_query_runs_read_only_with_the_row_cap() -> None: + node = FakeNode("4:g:1", frozenset({"Clause"}), {"key": "clause:1"}) + + def script(query: str, parameters: dict[str, Any], limit: int | None) -> Any: + assert "MATCH" in query and parameters == {"k": "clause:1"} and limit == 50 + return _rows(["n", "c"], [[node, 2]], truncated=True) + + graph, backend = _graph(script, max_rows=50) + reply = await graph.query( + {}, {"query": "MATCH (n {key: $k}) RETURN n, 2 AS c", "parameters": {"k": "clause:1"}} + ) + assert reply == { + "columns": ["n", "c"], + "rows": [[{"id": "4:g:1", "labels": ["Clause"], "properties": {"key": "clause:1"}}, 2]], + "truncated": True, + } + assert backend.modes == [False] + for body, message in ( + ({"query": "MATCH (n) SET n.x = 1 RETURN n"}, "query carries SET, a write clause"), + ({"query": " "}, "query must not be empty"), + ({"query": "MATCH (n) RETURN n", "parameters": [1]}, "parameters must be a map"), + ({"cypher": "MATCH (n) RETURN n"}, "graph_query does not take cypher"), + ): + status, text = await _astatus(graph.query({}, body)) + assert status == 400 and message in text, text + assert len(backend.transactions) == 1, "a refused query never reaches the database" + + +@pytest.mark.asyncio +async def test_graph_query_maps_a_database_failure() -> None: + import neo4j.exceptions as errors + + def script(_query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: + raise errors.Neo4jError._hydrate_neo4j( + code="Neo.ClientError.Statement.SyntaxError", message="Invalid input" + ) + + graph, _backend = _graph(script) + status, text = await _astatus(graph.query({}, {"query": "MATCH (n RETURN n"})) + assert status == 400 and text == "Neo.ClientError.Statement.SyntaxError: Invalid input" + + +@pytest.mark.asyncio +async def test_graph_write_returns_counters_and_guards_deletion( + caplog: pytest.LogCaptureFixture, +) -> None: + def script(query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: + assert query.startswith("CREATE INDEX") + return _rows([], [], counters={"indexes_added": 1}) + + graph, backend = _graph(script, write=True) + with caplog.at_level(logging.INFO): + reply = await graph.write( + {}, {"query": "CREATE INDEX clause_key FOR (n:Clause) ON (n.key)"} + ) + assert reply["counters"] == { + name: (1 if name == "indexes_added" else 0) for name in tools.COUNTER_NAMES + } + assert (reply["columns"], reply["rows"], reply["truncated"]) == ([], [], False) + assert backend.modes == [True] + assert "graph.write 200 indexes_added=1" in caplog.text + status, text = await _astatus(graph.write({}, {"query": "MATCH (n:Clause) DETACH DELETE n"})) + assert ( + status == 400 + and "query carries DELETE - deletion is not allowed" in text + and tools.GRAPH_DELETE in text + ) + status, text = await _astatus(graph.write({}, {"query": "DROP INDEX clause_key"})) + assert status == 400 and "DROP" in text + allowed, backend = _graph( + lambda q, p, limit: _rows([], [], counters={"nodes_deleted": 3}), write=True, delete=True + ) + reply = await allowed.write({}, {"query": "MATCH (n:Clause) DETACH DELETE n"}) + assert reply["counters"]["nodes_deleted"] == 3 + + +@pytest.mark.asyncio +async def test_graph_ingest_merges_nodes_then_checks_endpoints_then_merges_relationships() -> None: + def script(query: str, parameters: dict[str, Any], _limit: int | None) -> Any: + if query == tools.ENDPOINTS_QUERY: + assert parameters == {"keys": ["clause:1", "party:a"]} + return _rows(["key"], []) + return _rows([], [], counters={"nodes_created": 1}) + + graph, backend = _graph(script, write=True) + body = { + "nodes": [ + {"key": "clause:1", "label": "Clause", "properties": {"text": "pay within 30 days"}}, + {"key": "party:a", "label": "Party"}, + ], + "relationships": [{"from": "clause:1", "to": "party:a", "type": "BINDS"}], + "source": "contracts/a.md", + } + assert await graph.ingest({}, body) == {"nodes": 2, "relationships": 1} + queries = [call[0] for call in backend.calls] + assert [q.split(" ")[0] if q != tools.ENDPOINTS_QUERY else "CHECK" for q in queries] == [ + "UNWIND", + "UNWIND", + "CHECK", + "UNWIND", + ] + assert ( + "MERGE (n:`Clause`" in queries[0] + and "MERGE (n:`Party`" in queries[1] + and "MERGE (a)-[r:`BINDS`]->(b)" in queries[3] + ) + assert backend.calls[0][1] == { + "rows": [{"key": "clause:1", "properties": {"text": "pay within 30 days"}}], + "source": "contracts/a.md", + } + assert backend.modes == [True], "one write transaction" + # the same ingest again runs the same statements - idempotence is the MERGE's + assert await graph.ingest({}, body) == {"nodes": 2, "relationships": 1} + + +@pytest.mark.asyncio +async def test_graph_ingest_refuses_a_missing_endpoint_before_any_relationship_is_written() -> None: + def script(query: str, _parameters: dict[str, Any], _limit: int | None) -> Any: + if query == tools.ENDPOINTS_QUERY: + return _rows(["key"], [["ghost:1"]]) + return _rows([], []) + + graph, backend = _graph(script, write=True) + status, text = await _astatus( + graph.ingest( + {}, + { + "nodes": [{"key": "clause:1", "label": "Clause"}], + "relationships": [{"from": "clause:1", "to": "ghost:1", "type": "BINDS"}], + }, + ) + ) + assert ( + status == 400 + and text == "relationship endpoints not found in the graph or in this call: ghost:1" + ) + assert [q for q in (call[0] for call in backend.calls) if "MERGE (a)" in q] == [], ( + "no relationship statement ran" + ) + status, text = await _astatus(graph.ingest({}, {"nodes": [{"key": "k", "label": "Bad Label"}]})) + assert status == 400 and "identifier" in text + assert len(backend.transactions) == 1, "a refused ingest never reaches the database" + + +def test_graph_sandbox_address_hides_the_credential() -> None: + sandbox = tools.GraphSandbox(uri="neo4j+s://user:secret@graph.example:7687/x?y=1") + assert sandbox.address == "neo4j+s://graph.example:7687" + + +# --- file.extract -------------------------------------------------------------------------------- + + +def _pdf(pages: list[str]) -> bytes: + """A minimal PDF with one line of text per page, with a correct cross-reference table.""" + objects: list[bytes] = [] + page_ids = [4 + 2 * i for i in range(len(pages))] + kids = " ".join(f"{pid} 0 R" for pid in page_ids) + objects.append(b"<< /Type /Catalog /Pages 2 0 R >>") + objects.append(f"<< /Type /Pages /Kids [{kids}] /Count {len(pages)} >>".encode()) + objects.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>") + for index, text in enumerate(pages): + content = f"BT /F1 12 Tf 72 712 Td ({text}) Tj ET".encode() + objects.append( + f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> " + f"/Contents {page_ids[index] + 1} 0 R >>".encode() + ) + objects.append( + b"<< /Length " + + str(len(content)).encode() + + b" >>\nstream\n" + + content + + b"\nendstream" + ) + out = bytearray(b"%PDF-1.4\n") + offsets: list[int] = [] + for number, body in enumerate(objects, start=1): + offsets.append(len(out)) + out += f"{number} 0 obj\n".encode() + body + b"\nendobj\n" + xref = len(out) + out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode() + for offset in offsets: + out += f"{offset:010d} 00000 n \n".encode() + out += ( + f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode() + ) + return bytes(out) + + +def _docx(paragraphs: list[str], table: list[list[str]] | None = None) -> bytes: + import docx + + document = docx.Document() + for text in paragraphs: + document.add_paragraph(text) + if table: + grid = document.add_table(rows=len(table), cols=len(table[0])) + for r, row in enumerate(table): + for c, cell in enumerate(row): + grid.cell(r, c).text = cell + buffer = io.BytesIO() + document.save(buffer) + return buffer.getvalue() + + +@pytest.fixture +def documents(workspace: Path, files: Any) -> Any: + (workspace / "docs").mkdir() + (workspace / "docs" / "agreement.pdf").write_bytes( + _pdf( + [ + "Hello page one", + "Second page here", + "Third and last page of the agreement, with more words", + ] + ) + ) + (workspace / "docs" / "policy.docx").write_bytes( + _docx(["Policy title", "Pay within thirty days."], [["Party", "Role"], ["A", "Supplier"]]) + ) + (workspace / "docs" / "page.html").write_text( + "T

Heading

Body text.

", + encoding="utf-8", + ) + (workspace / "docs" / "archive.zip").write_bytes(b"PK\x03\x04" + b"\x00" * 30) + return files + + +def test_extract_a_pdf_with_page_markers_and_a_range(documents: Any) -> None: + reply = documents.extract({}, {"path": "docs/agreement.pdf"}) + assert (reply["path"], reply["type"], reply["pages"], reply["truncated"]) == ( + "docs/agreement.pdf", + "pdf", + 3, + False, + ) + assert ( + reply["text"] + == "--- page 1 ---\nHello page one\n\n--- page 2 ---\nSecond page here\n\n--- page 3 ---\nThird and last page of the agreement, with more words" + ) + assert ( + documents.extract({}, {"path": "docs/agreement.pdf", "pages": "2"})["text"] + == "--- page 2 ---\nSecond page here" + ) + ranged = documents.extract({}, {"path": "docs/agreement.pdf", "pages": "3, 1-2, 9"}) + assert [line for line in ranged["text"].splitlines() if line.startswith("---")] == [ + "--- page 3 ---", + "--- page 1 ---", + "--- page 2 ---", + ] + cut = documents.extract({}, {"path": "docs/agreement.pdf", "max_chars": 100}) + assert len(cut["text"]) == 100 and cut["truncated"] is True + + +def test_extract_word_html_and_text_documents(documents: Any) -> None: + word = documents.extract({}, {"path": "docs/policy.docx"}) + assert (word["type"], word["pages"]) == ("docx", 1) + assert ( + word["text"] + == "--- page 1 ---\nPolicy title\n\nPay within thirty days.\n\nParty | Role\nA | Supplier" + ) + html = documents.extract({}, {"path": "docs/page.html"}) + assert (html["type"], html["text"]) == ("html", "--- page 1 ---\nHeading\n\nBody text.") + text = documents.extract({}, {"path": "notes/plan.md"}) + assert (text["type"], text["text"]) == ("text", "--- page 1 ---\n# Plan\n\nWrite the tools.") + + +@pytest.mark.parametrize( + ("body", "status", "message"), + [ + ({"path": "data/image.png"}, 400, "not a PDF, Word, HTML or text document (a PNG image)"), + ({"path": "docs/archive.zip"}, 400, "not a PDF, Word, HTML or text document"), + ( + {"path": "docs/agreement.pdf", "pages": "x"}, + 400, + "pages must be page numbers and ranges", + ), + ({"path": "docs/agreement.pdf", "pages": "0"}, 400, "counted from 1"), + ({"path": "docs/agreement.pdf", "pages": "3-1"}, 400, "counted from 1"), + ({"path": "docs/agreement.pdf", "pages": 2}, 400, "pages must be a string"), + ({"path": "docs/agreement.pdf", "max_chars": 10}, 400, "max_chars must be at least 100"), + ({"path": "docs/missing.pdf"}, 404, "file not found"), + ({"path": "docs"}, 400, "is a directory"), + ({"path": "../outside/secret.txt"}, 400, "outside the workspace"), + ], +) +def test_extract_refuses_by_rule( + documents: Any, body: dict[str, Any], status: int, message: str +) -> None: + got = _status(lambda: documents.extract({}, body)) + assert got[0] == status, got + assert message in got[1], got + + +def test_page_range_and_document_kind() -> None: + assert tools.page_range(None, 3) == [1, 2, 3] + assert tools.page_range(" ", 2) == [1, 2] + assert tools.page_range("2-9", 3) == [2, 3] + assert tools.page_range("1,1,2", 3) == [1, 2] + assert tools.page_range("1-3", 0) == [] + assert tools.document_kind(b"%PDF-1.7 ...", ".pdf") == "pdf" + assert tools.document_kind(b"", ".txt") == "html" + assert tools.document_kind(b"plain words", ".htm") == "html" + assert tools.document_kind(b"plain words", ".md") == "text" + assert tools.document_kind(b"\x89PNG\r\n", ".png") is None + assert tools.document_kind(_docx(["x"]), ".docx") == "docx" + + +# --- the boot with the graph and the documents -------------------------------------------------- + + +class FakeBolt(FakeBackend): + def __init__(self, sandbox: Any): + super().__init__(lambda q, p, limit: _rows([], [])) + self.sandbox = sandbox + + +@pytest.mark.asyncio +async def test_the_graph_tools_register_by_the_uri_and_the_write_gate( + configure: Callable[[dict[str, Any]], None], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + monkeypatch.setattr(tools, "Bolt", FakeBolt) + configure( + { + tools.GRAPH_URI: "bolt://graph.example:7687", + tools.GRAPH_USERNAME: "neo4j", + tools.GRAPH_PASSWORD: "a-value-never-logged", + tools.TIME_ENABLED: False, + } + ) + reads = tools.AgentTools(FunctionRegistry()) + with caplog.at_level(logging.INFO): + await reads.boot() + assert reads.registered == ["graph.schema", "graph.query"] + assert "graph.write and graph.ingest not registered - tools.graph.write is false" in caplog.text + assert "Graph tools registered - bolt://graph.example:7687" in caplog.text + assert "a-value-never-logged" not in caplog.text + assert reads.graph is not None and reads.graph.sandbox.password == "a-value-never-logged" + await reads.shutdown() + assert reads.graph.backend.closed + configure({tools.GRAPH_WRITE: "true", tools.GRAPH_DELETE: True}) + writes = tools.AgentTools(FunctionRegistry()) + with caplog.at_level(logging.INFO): + await writes.boot() + assert writes.registered == ["graph.schema", "graph.query", "graph.write", "graph.ingest"] + assert "writes allowed, deletion allowed" in caplog.text + monkeypatch.setattr(tools, "agent_tools", writes) + info = await tools.tools_health({"type": "info"}, None) + assert info["graph"] == "bolt://graph.example:7687" and info["tools"] == writes.registered + + +@pytest.mark.asyncio +async def test_a_graph_that_does_not_answer_at_boot_is_logged_not_fatal( + configure: Callable[[dict[str, Any]], None], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + class Unreachable(FakeBolt): + async def verify(self) -> None: + raise OSError("connection refused") + + monkeypatch.setattr(tools, "Bolt", Unreachable) + configure({tools.GRAPH_URI: "bolt://graph.example:7687", tools.TIME_ENABLED: False}) + app = tools.AgentTools(FunctionRegistry()) + with caplog.at_level(logging.WARNING): + await app.boot() + assert app.registered == ["graph.schema", "graph.query"] + assert "does not answer yet (OSError); calls fail until it does" in caplog.text + + +@pytest.mark.asyncio +async def test_a_bad_graph_configuration_stops_the_boot_by_name( + configure: Callable[[dict[str, Any]], None], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + configure({tools.GRAPH_URI: "http://graph.example:7474"}) + with caplog.at_level(logging.ERROR), pytest.raises(SystemExit): + await tools.AgentTools(FunctionRegistry()).boot() + assert "tools.graph.uri must be a Bolt URI" in caplog.text + configure({tools.GRAPH_URI: "bolt://graph.example:7687"}) + monkeypatch.setattr(tools, "neo4j", None) + with caplog.at_level(logging.ERROR), pytest.raises(SystemExit): + await tools.AgentTools(FunctionRegistry()).boot() + assert ( + "the Bolt driver is not installed - pip install 'mercury-composable[graph]'" in caplog.text + ) + + +@pytest.mark.asyncio +async def test_file_extract_registers_only_with_the_documents_extra( + workspace: Path, + configure: Callable[[dict[str, Any]], None], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + configure({tools.FILE_ROOT: str(workspace), tools.TIME_ENABLED: False}) + with_documents = tools.AgentTools(FunctionRegistry()) + await with_documents.boot() + assert "file.extract" in with_documents.registered + monkeypatch.setattr(tools, "pypdf", None) + without = tools.AgentTools(FunctionRegistry()) + with caplog.at_level(logging.INFO): + await without.boot() + assert "file.extract" not in without.registered + assert ( + "file.extract not registered - pip install 'mercury-composable[documents]'" in caplog.text + ) + assert tools.describe(["file_extract"]) == 0 + + +def test_describe_states_for_the_graph_and_the_documents( + capsys: pytest.CaptureFixture[str], configure: Callable[[dict[str, Any]], None] +) -> None: + configure({tools.GRAPH_URI: "bolt://graph.example:7687"}) + assert tools.describe(["graph_query", "graph_write"]) == 0 + out = capsys.readouterr().out + assert "## graph.query (graph_query) - registers (bolt://graph.example:7687)" in out + assert "## graph.write (graph_write) - NOT registered (tools.graph.write is false)" in out + configure({tools.GRAPH_WRITE: True}) + assert tools.describe(["graph_ingest"]) == 0 + assert ( + "## graph.ingest (graph_ingest) - registers (bolt://graph.example:7687)" + in capsys.readouterr().out + ) + + +# --- the live graph (gated) --------------------------------------------------------------------- + + +@pytest.mark.skipif( + not os.environ.get("TOOLS_GRAPH_TEST_URI"), + reason="a live graph database: set TOOLS_GRAPH_TEST_URI (and TOOLS_GRAPH_TEST_PASSWORD, TOOLS_GRAPH_TEST_USER), " + "e.g. the one extensions/agent-tools/dev/graph-up.sh starts", +) +@pytest.mark.asyncio +async def test_live_graph_round_trip(configure: Callable[[dict[str, Any]], None]) -> None: + configure( + { + tools.GRAPH_URI: os.environ["TOOLS_GRAPH_TEST_URI"], + tools.GRAPH_USERNAME: os.environ.get("TOOLS_GRAPH_TEST_USER", "neo4j"), + tools.GRAPH_PASSWORD: os.environ.get("TOOLS_GRAPH_TEST_PASSWORD", ""), + tools.GRAPH_WRITE: True, + tools.GRAPH_DELETE: True, + } + ) + graph = tools.GraphTools(tools.load_graph_sandbox()) + cleanup = "MATCH (n) WHERE n:T_Clause OR n:T_Party DETACH DELETE n" + body = { + "nodes": [ + { + "key": "t_clause:1", + "label": "T_Clause", + "properties": {"text": "pay within 30 days", "days": 30}, + }, + {"key": "t_party:a", "label": "T_Party", "properties": {"name": "supplier a"}}, + ], + "relationships": [ + { + "from": "t_clause:1", + "to": "t_party:a", + "type": "T_BINDS", + "properties": {"since": 2026}, + } + ], + "source": "contracts/a.md", + } + try: + await graph.backend.verify() + await graph.write({}, {"query": cleanup}) + assert await graph.ingest({}, body) == {"nodes": 2, "relationships": 1} + assert await graph.ingest({}, body) == {"nodes": 2, "relationships": 1}, "idempotent" + count = await graph.query({}, {"query": "MATCH (n:T_Clause) RETURN count(n) AS c"}) + assert count["rows"] == [[1]], "the second ingest created nothing" + rows = await graph.query( + {}, + { + "query": "MATCH (a:T_Clause)-[r:T_BINDS]->(b) RETURN a, r, b, a.days + $x AS sum", + "parameters": {"x": 1}, + }, + ) + node, relationship, party, total = rows["rows"][0] + assert ( + node["labels"] == ["T_Clause"] + and node["properties"]["key"] == "t_clause:1" + and node["properties"]["source"] == "contracts/a.md" + ) + assert ( + relationship["type"] == "T_BINDS" + and relationship["start"] == node["id"] + and relationship["end"] == party["id"] + ) + assert ( + relationship["properties"] == {"since": 2026, "source": "contracts/a.md"} + and total == 31 + ) + path = await graph.query( + {}, {"query": "MATCH p = (:T_Clause)-[:T_BINDS]->(:T_Party) RETURN p"} + ) + assert [item.get("labels", item.get("type")) for item in path["rows"][0][0]] == [ + ["T_Clause"], + "T_BINDS", + ["T_Party"], + ] + schema = await graph.schema({}, None) + clause = next(label for label in schema["labels"] if label["label"] == "T_Clause") + assert clause["count"] == 1 and {p["name"] for p in clause["properties"]} >= { + "key", + "text", + "days", + "source", + } + binds = next(kind for kind in schema["relationship_types"] if kind["type"] == "T_BINDS") + assert (binds["count"], binds["from"], binds["to"]) == (1, ["T_Clause"], ["T_Party"]) + status, text = await _astatus( + graph.query({}, {"query": "MATCH (n:T_Clause) SET n.x = 1 RETURN n"}) + ) + assert status == 400 and "write clause" in text + status, text = await _astatus(graph.query({}, {"query": "MATCH (n:T_Clause RETURN n"})) + assert status == 400 and text.startswith("Neo.ClientError.Statement.SyntaxError") + status, text = await _astatus( + graph.ingest( + {}, {"relationships": [{"from": "t_clause:1", "to": "ghost:9", "type": "T_BINDS"}]} + ) + ) + assert status == 400 and "ghost:9" in text + guarded = tools.GraphTools( + tools.GraphSandbox( + uri=graph.sandbox.uri, + username=graph.sandbox.username, + password=graph.sandbox.password, + write=True, + ) + ) + try: + status, text = await _astatus(guarded.write({}, {"query": cleanup})) + assert status == 400 and "deletion is not allowed" in text + finally: + await guarded.close() + deleted = await graph.write({}, {"query": cleanup}) + assert ( + deleted["counters"]["nodes_deleted"] == 2 + and deleted["counters"]["relationships_deleted"] == 1 + ) + finally: + await graph.close() From 8e2d8d18c402add5aacfcc8e6d892f4fa5dde63f Mon Sep 17 00:00:00 2001 From: Eric Law <39393654+acn-ericlaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:42:29 +0800 Subject: [PATCH 2/2] memory: RFC-0013 step 2 opened as PR #64 Co-Authored-By: Claude Fable 5.1 --- memory/open-threads/thread-bp-agent-tools-python.md | 4 ++-- memory/sessions/2026-11-17-104217.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/memory/open-threads/thread-bp-agent-tools-python.md b/memory/open-threads/thread-bp-agent-tools-python.md index 540efa1..5de947a 100644 --- a/memory/open-threads/thread-bp-agent-tools-python.md +++ b/memory/open-threads/thread-bp-agent-tools-python.md @@ -7,8 +7,8 @@ pinned, a write bounded by `tools.file.max.bytes`, no `strict` on the rows, the statuses, row names = routes with `_`). In passing: the MCP binding's direct run never attached its boot hook (fixed; the Node binding attaches its hooks on both paths - checked 2026-11-17, nothing to do there). The engines' page `docs/guides/agent-tools.md` - landed as mercury-composable #644. **Step 2 BUILT 2026-11-17** (PR - opened the same day): the four graph tools over the Bolt driver (`graph` extra; a `Transaction` seam, a fake for the + landed as mercury-composable #644. **Step 2 BUILT 2026-11-17** as PR #64 (branch + `feat/agent-tools-graph`): the four graph tools over the Bolt driver (`graph` extra; a `Transaction` seam, a fake for the tests, Neo4j and Memgraph schema procedures), `file.extract` behind the `documents` extra, `dev/graph-up.sh` / `graph-down.sh`, 161 tests and a live round trip on the development Neo4j; eight defaults set without a ruling in the session log. Next: the engines' page and spec for step 2, then the Node twin. The plan as settled - step 1: `extensions/agent-tools/agent_tools.py` (the layout of `extensions/mcp-binding`: a module docstring, a diff --git a/memory/sessions/2026-11-17-104217.md b/memory/sessions/2026-11-17-104217.md index eea057e..ee9234d 100644 --- a/memory/sessions/2026-11-17-104217.md +++ b/memory/sessions/2026-11-17-104217.md @@ -49,7 +49,7 @@ 8. `file.extract` returns `type` (`pdf`, `docx`, `html`, `text`) and the document's page count; a Word document is one page; `tools.file.extract.max.chars` (60 000) is the cap key the paper did not name. -Next: the engines' page and the spec's section 14 for step 2, then the Node twin (step 3; check its MCP binding's +Opened as PR #64. Next: the engines' page and the spec's section 14 for step 2, then the Node twin (step 3; check its MCP binding's direct-run hook too), the Playground graphs and the recipes (steps 4-5). ## Memory References