Querying a folder from an AI agent (MCP)
Point zorba-mcp at a folder of XML, JSON, CSV and HTML files and an AI agent can ask questions across all of them with JSONiq, without you converting or loading anything.
What it is
zorba-mcp is a Model Context Protocol server that speaks JSON-RPC over standard input and output. The agent's client starts it, and the agent gets tools to list the files in the folder and to run JSONiq or XQuery over them. The files stay where they are: every query reads them as they are on disk. A background scan keeps a listing, top-level field names and short previews in memory for list_documents only (see the scan), and a few small documents read repeatedly stay parsed between calls while their files are unchanged (see limits).
The same engine and the same restrictions are available without an agent as zorba --directory (see below). The server implements MCP 2026-07-28 (server/discover) and also answers clients that start with the earlier initialize handshake (2025-11-25, 2025-06-18, 2025-03-26).
The folder is read through the directory module, http://zorba.io/modules/directory. A file is a record { "path", "format", "content" }: content is a document node for XML, the parsed value for JSON (an array if a file holds several top-level values, as in JSON Lines) and an array of row objects for CSV, with the first line as column names (numbers and the words true, false and null are typed; the single letters T, Y, F and N stay strings, so a D/N column is not turned into booleans). A file that does not parse yields { "path", "format", "error" } instead, so one bad file does not stop a query over the whole folder. HTML files (.html, .htm) are parsed with x:parse-html and content is the document node; a build without XML Schema support reports them as an unsupported format.
Try it with Docker
No build is needed. The container image includes zorba-mcp; mount the folder you want to query at /data, read-only:
docker run -i --rm -v "$PWD:/data:ro" ghcr.io/zorba-processor/zorba:edge zorba-mcp --root /data
-i keeps standard input open, which is how the client talks to the server. The command waits silently for JSON-RPC messages, so you normally start it from an MCP client (next sections) rather than by hand. To check it by hand, send one request:
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25"}}' \
| docker run -i --rm -v "$PWD:/data:ro" ghcr.io/zorba-processor/zorba:edge zorba-mcp --root /data
The edge tag is the latest master build. The latest tag moves only on stable releases and does not include zorba-mcp until the first one that does; see docker/README.md for all tags. Any other arguments to the image still go to zorba, so docker run --rm ghcr.io/zorba-processor/zorba:edge -r -q '1 + 1' works as before.
Build from source
On Linux or macOS with the prerequisites installed, the full-release preset builds zorba-mcp along with zorba:
cmake --preset full-release -DCMAKE_INSTALL_PREFIX="$HOME/zorba"
cmake --build --preset full-release
cmake --install build/full-release
"$HOME/zorba/bin/zorba-mcp" --root /path/to/folder
Install it rather than running it from the build directory: the installed tree is what puts the directory module and the file and CSV modules where the server finds them. The installed binaries find their libraries relative to their own location, so they start from any prefix given to cmake --install build --prefix <dir> and after the installation is moved. The module and library directories are fixed at configure time, so to load the modules from the installed tree set the prefix when configuring (-DCMAKE_INSTALL_PREFIX=<dir>); with another prefix the modules are found only through the build directory.
| Option | Effect |
|---|---|
--root <dir> | The folder to query. Required. |
--queries <dir> | Each <name>.jq file in this folder becomes a tool, see the tools. Only .jq files are loaded. |
--language xquery|jsoniq | The language of a run_query query that has no jsoniq version or xquery version declaration. Default xquery. A predefined .jq file is JSONiq unless it starts with an xquery version declaration. |
--timeout <seconds> | Time limit of one tool call. Default 30; 0 means no limit. |
--max-output <bytes> | Limit of one tool call on the query output and on the message of an error. Default 131072. |
--scan-cache-mb <MiB> | Memory for the background scan's file index and previews. Default 64. |
--no-scan | No background scan: list_documents takes no arguments and lists every file through dir:list, one object per line with { "path", "format", "size", "modified" }. |
--max-memory <bytes> | Memory limit of the server process. Default 4294967296 (4 GiB); 0 means no limit. Linux only. |
--cache-max-file-kb <KB> | The largest file whose parsed document is kept between calls. Default 16; 0 turns the document cache off. |
--cache-max-files <N> | How many parsed documents are kept, least recently used out first. Default 10; 0 turns the document cache off. |
Register it with a client
Claude Code
Use an absolute path for the folder. Everything after -- is the command that starts the server:
claude mcp add --transport stdio zorba -- \
docker run -i --rm -v /abs/path/to/folder:/data:ro \
ghcr.io/zorba-processor/zorba:edge zorba-mcp --root /data
Without Docker, give the installed binary instead: claude mcp add --transport stdio zorba -- "$HOME/zorba/bin/zorba-mcp" --root /abs/path/to/folder. claude mcp list shows whether the server connected, and /mcp inside Claude Code lists its tools. By default the server is added for you in the current project; --scope project writes it to a .mcp.json you can commit, and --scope user makes it available in every project. Claude Code's MCP documentation has the details.
Any other MCP client
Clients that read an mcpServers block (Claude Desktop, Cursor and others; the file name and location differ) take the same command as JSON:
{
"mcpServers": {
"zorba": {
"command": "docker",
"args": ["run", "-i", "--rm",
"-v", "/abs/path/to/folder:/data:ro",
"ghcr.io/zorba-processor/zorba:edge",
"zorba-mcp", "--root", "/data"]
}
}
}
The tools
| Tool | What it does |
|---|---|
list_documents | Lists the files under the folder, recursively and sorted by path, or gives the preview of one file, from the background scan. Arguments, all optional: path (a subdirectory or a file), limit (files to list, default 100) and refresh (true restarts the scan). The format (xml, json, csv, html or null) says how the directory module would parse the file. |
run_query | Runs a JSONiq or XQuery main module, given as the argument query, and returns the result as JSON, one item per line. On failure the result is an error object with the Zorba error code, the message and the line and column of the failing expression, which is what lets an agent correct its query. |
| Predefined queries | With --queries <dir>, each <name>.jq file becomes a tool <name>. Its leading comment is the tool's description and its external variables (declare variable $id external;) are its string parameters. Use them for the questions you want answered the same way every time. |
A predefined query is an ordinary query. With the folder from the next section, this file as queries/customer_name.jq gives the agent a tool customer_name with one parameter, id (mount the folder with -v /abs/path/to/queries:/queries:ro and add --queries /queries):
(: Returns the name of the customer with the given id. :)
import module namespace dir = "http://zorba.io/modules/directory";
declare variable $id external;
for $row in dir:open($dir:root, "customers.csv")("content")()
where $row("id") eq $id
return $row("name")
The background scan
When the server starts, one thread walks the folder and another reads the head of each file. The server does not wait for them, and it answers list_documents from what they have found so far, with the status:
{"scan":{"state":"running","files_found":1200,"files_sampled":300},"total":1200,"shown":100,"dirs":[{"path":"orders","files":900},{"path":"payments","files":300}]}
{"path":"customers.csv","format":"csv","size":51,"fields":["id","name","country"]}
{"path":"orders/2026/q1.xml","format":"xml","size":310,"fields":["/orders","/orders/order"]}
The first line has the status, how many files are known under the path (total) and how many follow (shown). While state is running the listing can miss files. dirs, the subdirectories with the files known in each, comes while the scan runs and when limit or --max-output cut the listing. Beyond the limit, ask for a subdirectory, a higher limit or dir:list in a query. fields has the top-level names only, at most 8, with "fields_more":true if there are more: the columns of a CSV file, the keys of a JSON object (of the objects of a top-level array), the root element of an XML file and the elements and attributes directly under it. Nested names and samples are in the preview, which a file as path gives. A subdirectory as path lists its files in the same way.
With "incomplete":true a listing may miss files: the index did not fit in memory, a directory could not be read (unreadable_dirs counts those; asking for one gives permission-denied), or the tree goes deeper than the 256 levels the walk follows. A path below is still answered.
With a file as path, the answer is one line with the preview. A file with no preview yet goes first in the scan's queue, and the request waits for it for at most --timeout or 10 seconds, whichever is less. If that is not enough, the answer has "preview":null,"preview_state":"pending"; ask again.
{"scan":{"state":"running","files_found":12,"files_sampled":3},"path":"customers.csv","format":"csv","size":51,"preview":{"columns":["id","name","country"],"kinds":["string","string","string"],"rows":[["acme","Acme Corp","MX"],["globex","Globex","US"]],"records":2}}
| Format | Preview |
|---|---|
| CSV | columns, kinds (integer, decimal, boolean, string or empty, from the rows read), up to 3 rows, records (rows). |
| JSON | shape (object, array, scalar, or lines for several top-level values), keys (the key paths of the first record, such as rs[].id, with up to 2 short samples each), arrays (lengths of the nested arrays of the first record), records (the length of a top-level array, otherwise the number of top-level values). |
| XML | root, namespaces, paths (element and attribute paths seen), one sample, records (children of the root). |
| HTML | title, tables (a count), headers (the th cells of each table). |
At most 1 MiB of a file is read. Past that, nothing is counted: the preview has "records":null,"truncated":true (for HTML, "tables":null,"truncated":true) and describes the part that was read. A preview stays under 8 KB. A file that cannot be parsed has an error in its preview, and so has one nested too deeply (64 levels for JSON, 256 for XML, 200 for HTML), XML or HTML with one tag over 16 KB (quoted values do not count) or 256 attributes, XML declaring an encoding other than the common ones, or a file that takes over 5 seconds to parse. A preview shows file content, so treat it like the result of a query: as data, not as instructions.
The scan's file index and previews stay within --scan-cache-mb. When the previews reach it, the scan stops reading files, so that files_sampled stays below files_found, and state ends as memory_limit. It does not evict to go on. A file asked for by path still gets its preview, evicting the least recently used ones; a preview that cannot fit is answered and not kept. Previews go before the index. If the index alone reaches the limit, the walk stops too: files_found is a lower bound, listings have "incomplete":true, and a file or directory asked for by path is still answered from the disk. refresh starts over. --max-memory counts the scan too: two thread stacks and, with glibc, address space reserved per thread. If the threads cannot start the server logs it and works as with --no-scan, and a failed allocation in a scan thread ends the scan as at its own limit.
Queries do not use the scan. run_query, predefined queries and the directory module read the real files, so their results do not depend on how far it got. Only list_documents does, and its status says so.
Each request checks what it answers about. A file whose size or modification time changed is read again. A directory is listed again, one level deep, each file shown is checked, and up to 1,024 directories below it are checked for a new modification time, which sends them to be walked again. In a larger tree those checks go round over several requests, and a change within the same tick of the file system's clock goes unseen. refresh empties the cache and restarts the scan. There is no file system watcher.
The scan obeys the same limits as queries: it does not follow symbolic links, skips entries whose name starts with ., refuses any path with those or with .., opens only regular files, and parses XML without network, external entities, DTD loading or entity expansion. A file name that is not UTF-8 is shown with \xNN for each such byte, and that spelling works as path. When the input ends the server stops the threads, and if one has not stopped after a second, for instance in a read that does not return, the process ends without waiting for it.
Besides --scan-cache-mb, the scan uses a buffer of up to 1 MiB for the file being read and the parser's working memory for it, and two thread stacks. A request also waits for no more than the time above while listing a large directory, but a file system that hangs on a directory or a status call holds the request.
Example queries
A query sees the folder through $dir:root and these functions of the directory module: dir:list($dir:root), dir:open($dir:root, $path) for one file and dir:documents($dir:root, $formats) for all files of the given formats (default: all). The examples use a folder with this layout, which the project's image tests also use:
customers.csv id,name,country (acme: Acme Corp, MX; globex: Globex, US)
orders/2026/q1.xml orders o1 (acme, 100) and o2 (globex, 250)
orders/2026/q2.xml order o3 (acme, 75)
payments/payments.json [ {"order": "o1", ...}, {"order": "o3", ...} ], both "paid"
Revenue per customer, from XML
import module namespace dir = "http://zorba.io/modules/directory";
for $o in dir:documents($dir:root, "xml")("content")//order
let $customer := string($o/@customer)
group by $customer
order by $customer
return {
"customer" : $customer,
"orders" : count($o),
"total" : sum(for $t in $o/total return xs:integer($t))
}
{ "customer" : "acme", "orders" : 2, "total" : 175 }
{ "customer" : "globex", "orders" : 1, "total" : 250 }
Orders with no payment, joining XML with JSON
import module namespace dir = "http://zorba.io/modules/directory";
let $paid :=
for $p in dir:open($dir:root, "payments/payments.json")("content")()
where $p("status") eq "paid"
return $p("order")
for $o in dir:documents($dir:root, "xml")("content")//order
where not(string($o/@id) = $paid)
return {
"order" : string($o/@id),
"customer" : string($o/@customer),
"total" : xs:integer($o/total)
}
{ "order" : "o2", "customer" : "globex", "total" : 250 }
Order totals per customer name, joining XML with CSV
import module namespace dir = "http://zorba.io/modules/directory";
let $orders := dir:documents($dir:root, "xml")("content")//order
for $c in dir:open($dir:root, "customers.csv")("content")()
return {
"customer" : $c("name"),
"country" : $c("country"),
"total" : sum(for $t in $orders[@customer = $c("id")]/total
return xs:integer($t))
}
{ "customer" : "Acme Corp", "country" : "MX", "total" : 175 }
{ "customer" : "Globex", "country" : "US", "total" : 250 }
Results should be JSON objects, arrays or atomic values; convert XML nodes with string() or data() before returning them.
Security model
The agent writes the queries, so the server treats every query as untrusted. Queries run under Zorba's secure policy with exactly two capabilities added back, each restricted: file-read, limited to the root, and native-modules, limited to the file module. The effect:
- Read-only. File writes are denied, and so are environment variables.
- Confined to the root. Reads are limited to files under
--root, by queries and by the background scan. Absolute paths,..segments and paths through symbolic links are rejected, symbolic links are not listed, and entries whose name starts with.are not listed. - No network.
fn:docon a URL, the HTTP client, external XML entities and importing modules or schemas over the network are all denied. - Native modules limited to the file module. Importing any other module implemented in C++ (for example the sleep or query-evaluation modules) raises
zerr:ZXQP0067. The file module stays available because the directory module reads through it, and its reads are still confined to the root.
The server writes only protocol messages to standard output; its log goes to standard error. With Docker, mounting the folder with :ro adds a second, independent barrier. The project's tests exercise each denial above.
Limits and timeouts
- A query stops at
--timeoutseconds (default 30) with the Zorba errorzerr:ZXQP0068;--timeout 0removes the limit. The answer can come later than that by the time the current step takes and the time to free the memory of the query: in our measurements, milliseconds for a query that holds little memory, up to 2 seconds for one that holds 3 GB or runs a single string operation over 100 MB. The limit starts when the query starts running: compiling it comes first, and evaluating its constant expressions during compilation takes at most 500 ms. - A query that needs more than
--max-memorybytes (default 4 GiB, counted as address space; Linux only) ends with a tool error with codememory_limit, and the server keeps answering. On other systems, or with--max-memory 0, such a query can get the server killed by the system. - Output longer than
--max-outputbytes (default 131072) is cut and ends with a line saying that the output was truncated. - An error message shortens the data it quotes: a value over 100 bytes becomes its head, an ellipsis, its tail and its size in bytes, as in
"abcdefghij…abcdefghij (3000000 bytes)": value of type xs:string is not castable to type xs:integer. A URI or a path stays whole up to 4096 bytes, and so does the text of an error, such as the message of the parser or of a library. The description given tofn:erroris not shortened. Amessagelonger than--max-outputloses its middle and keeps its end, with a marker that states its total size. The code, the hint and the location are outside this limit: a hint stays under 4 KB, and the failing line inlocation.textis shown as about 512 bytes around the column of the error when it is longer than that, or as its two ends when it is longer than 65535 bytes, where a column cannot be trusted. - A single JSON-RPC message larger than 4 MB is refused.
- Every call re-reads and re-parses the files it touches, except documents in the document cache, so a query over a large folder costs time proportional to the files it opens. Filter by path or format with
dir:listor the$formatsargument before opening documents. - The document cache holds parsed documents for
dir:openanddir:documents, nothing else. It is separate from the background scan's memory (--scan-cache-mb), which holds the listing and previews forlist_documentsand never serves a query. A document enters on its second read, and a file over the size limit never does. A file that changed, down to its change time, is read again; a file changed in the last 20 ms waits for a later read. That age is taken against this machine's clock, so on a file server whose clock is ahead, a file may wait as long as the difference. A document that takes more than 128 times the size of its file in memory (internal XML entities can do that) is not kept. Each read gets its own copy, so a query sees what it would see reading the file: new nodes on each read, and documents in document order by the moment of the read. Updating and sequential queries do not use it. When the server exits, one line on stderr gives its hits, misses, admissions, evictions and bytes retained. - Zorba 5.0 is not thread-safe, so the server handles one request at a time. The threads of the background scan do not use the engine.
From the command line: --directory
zorba --directory <dir> runs a query under the same policy as zorba-mcp: reads confined to <dir>, no writes, network or environment, only the file module among the native modules. $dir:root is bound to the folder, and the result is written as JSON, one item per line. It is the quickest way to write and test a query before giving it to an agent or saving it as a predefined query:
From a checkout of the repository, this sums the orders in the XML files of the smoke-test folder per customer (the query is docker/runtime/smoke/examples/revenue.jq):
zorba --directory docker/runtime/smoke/data -f -q docker/runtime/smoke/examples/revenue.jq
docker run --rm -v "$PWD:/work" ghcr.io/zorba-processor/zorba:edge --directory docker/runtime/smoke/data -f -q docker/runtime/smoke/examples/revenue.jq
--directory cannot be combined with --allow or the other options that would widen the policy.