@infino-ai/mcp-server 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -5
- package/dist/agent-api.js +39 -3
- package/dist/index.js +159 -75
- package/dist/join-gate.js +432 -0
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
An [MCP](https://modelcontextprotocol.io) server for [Infino](https://github.com/infino-ai/infino) — it lets an AI agent run **keyword**, **semantic**, **hybrid**, and **SQL** retrieval over your data on object storage — the retrieval layer for RAG, persistent agent memory, and search over your own files — from any MCP-compatible client (Claude Code, Claude Desktop, Cursor, VS Code, and others). Published on npm as [`@infino-ai/mcp-server`](https://www.npmjs.com/package/@infino-ai/mcp-server) and listed on the [official MCP Registry](https://registry.modelcontextprotocol.io) as `io.github.infino-ai/mcp-server` (which propagates to catalogs like Smithery, Glama, and PulseMCP).
|
|
8
8
|
|
|
9
9
|
- **Local embeddings, no key.** Semantic search embeds queries with a local model — nothing leaves the machine for embedding.
|
|
10
|
-
- **The agent owns the data.** Every tool, writes included, is always available. On Infino Cloud the API key's capabilities decide what a connection may do; every tool carries MCP annotations so your client can ask before a destructive call.
|
|
10
|
+
- **The agent owns the data.** Every data tool, writes included, is always available. On Infino Cloud the API key's capabilities decide what a connection may do; every tool carries MCP annotations so your client can ask before a destructive call.
|
|
11
11
|
- **Local or hosted.** Point it at a local path, your own bucket (S3, Azure, or any S3-compatible store), or a hosted Infino Cloud endpoint with an API key.
|
|
12
12
|
- **The index is a valid Parquet file.** A table stores the data and its search indexes in plain Parquet on the storage — open the same file with DuckDB or pyarrow. No export, no lock-in.
|
|
13
13
|
|
|
@@ -201,6 +201,7 @@ All configuration is via environment variables — there are no config files and
|
|
|
201
201
|
| `INFINO_MCP_EMBED_API_KEY` | No | — | API key for the `openai` provider. Sent as both `Authorization: Bearer` and `api-key`, so one value works for OpenAI and Azure OpenAI. Omit to call an unauthenticated or ambient-identity endpoint. |
|
|
202
202
|
| `INFINO_MCP_EMBED_MODEL` | No | `Xenova/all-MiniLM-L6-v2` (local) · `text-embedding-3-small` (openai) | The embedding model. For `local`, a Hugging Face feature-extraction model; for `openai`, the model/deployment name. **Must match the model that produced the table's stored vectors** — and therefore its vector-index dimension (e.g. `text-embedding-3-small` is 1536-dim; the default local model is 384-dim). |
|
|
203
203
|
| `INFINO_MCP_VALIDATE` | No | _off_ | When set (`1`/`true`/`yes`), probes the object store at startup so bad credentials or an unreachable bucket fail then instead of on the first search. |
|
|
204
|
+
| `INFINO_MCP_ASK` | No | _off_ | When set (`1`/`true`/`yes`), offers `infino_ask` on an Infino Cloud account with the agent tools on. Each ask runs a model loop billed to the account. |
|
|
204
205
|
|
|
205
206
|
Cloud credentials are read from the standard provider environment variables — the server maps them to the store's config and introduces no credential vars of its own. Omit them entirely to use ambient cloud identity (an IAM instance role or Azure managed identity).
|
|
206
207
|
|
|
@@ -281,7 +282,7 @@ the data.
|
|
|
281
282
|
| `infino_token_match` | `table`, `query`, `column?`, `mode?`, `limit?` | Unranked keyword filter — the set of rows whose text column contains the token(s). Use when you need the matches, not a relevance order. |
|
|
282
283
|
| `infino_exact_match` | `table`, `value`, `column?`, `limit?` | Unranked exact-equality filter over an indexed column (tag, status, id string). |
|
|
283
284
|
| `infino_count` | `table`, `query`, `column?`, `mode?` | Count how many rows match a keyword query, without fetching them — a fast tally over the text column. For the matching rows use `infino_keyword_search` or `infino_token_match`. |
|
|
284
|
-
| `infino_sql` | `query`, `embed?` | SQL for counts, filters, joins, aggregates. The engine's search table functions are callable inside it; a `{{name}}` placeholder is filled with the vector of `embed[name]`. Any single statement, DDL/DML included. |
|
|
285
|
+
| `infino_sql` | `query`, `embed?`, `question?` | SQL for counts, filters, joins, aggregates. The engine's search table functions are callable inside it; a `{{name}}` placeholder is filled with the vector of `embed[name]`. Any single statement, DDL/DML included. On Infino Cloud, see [Checked SQL](#checked-sql-infino-cloud). |
|
|
285
286
|
| `infino_list_tables` | — | List the tables in the connected catalog. |
|
|
286
287
|
| `infino_describe_table` | `table` | Column names and types for a table. |
|
|
287
288
|
| `infino_create_database` | — | Provision the database the connection names (Infino Cloud); a no-op success locally. Idempotent. |
|
|
@@ -295,15 +296,21 @@ Search hits return **full column values** — the `columns` argument is a projec
|
|
|
295
296
|
|
|
296
297
|
For plain retrieval prefer the dedicated search tools, which embed and project for you. `infino_sql` is for filters, joins, and aggregates, including over a search table function's results, so one query can rank and aggregate at once.
|
|
297
298
|
|
|
299
|
+
### Checked SQL (Infino Cloud)
|
|
300
|
+
|
|
301
|
+
On a hosted connection, a read whose statement runs a text search (`bm25_search`, `bm25_search_prefix`, `hybrid_search`, `token_match` or `exact_match`) is sent to Infino Cloud with a check of its rows. The result carries `validation` beside the rows: whether they answer `question`, and, when they do not, the question's terms the searched column holds nowhere, so the agent knows no query will find them. A `GROUP BY` over a search function with a `k` under 300 is refused before it runs, because its totals rank a share of the top `k` rather than the table. The check's engine work is metered with the query. Statements without a text search, writes, and local or bucket connections run as before.
|
|
302
|
+
|
|
303
|
+
On an account with the agent tools on, a statement that joins tables is also held to the keys `infino_join_keys` finds on their values: one that joins them on other columns is refused, and the refusal names the keys to rewrite it on.
|
|
304
|
+
|
|
298
305
|
### Agent tools (Infino Cloud)
|
|
299
306
|
|
|
300
|
-
On a hosted connection, the server asks Infino Cloud once at startup whether the account has the agent tools switched on (`GET /v1/account/features`). When it does,
|
|
307
|
+
On a hosted connection, the server asks Infino Cloud once at startup whether the account has the agent tools switched on (`GET /v1/account/features`). When it does, `infino_describe_columns` and `infino_join_keys` appear, and `infino_ask` too when `INFINO_MCP_ASK` is set; otherwise, and on every local or bucket connection, they are not offered at all.
|
|
301
308
|
|
|
302
309
|
| Tool | Arguments | What it does |
|
|
303
310
|
| --- | --- | --- |
|
|
304
311
|
| `infino_describe_columns` | `table`, `pattern`, `limit?` | A table's column entries from the card Infino Cloud computed from the table itself: type, index role, rows with a value, distinct count, range and most frequent values. `pattern` is a column name or a `*` pattern (`property_*`, `*monthly*`). For wide tables, call it before a statement names a column. |
|
|
305
312
|
| `infino_join_keys` | `tables` (2 to 8) | The keys the tables join on, found on their values rather than by column name, each with its `predicate`, the `ON` clause to paste into `infino_sql`. |
|
|
306
|
-
| `infino_ask` | `question`, `table?`, `tables?`, `k?`, `context?`, `maxWallSecs?` | A plain-language question answered by a retrieval agent on Infino Cloud, which runs the searches and SQL itself and returns the rows it found (`facts`), the statement whose rows answer the question (`statement`) and `coverage`, never a summary. Each ask runs a model loop billed to the account and takes seconds to a few minutes; when you already know the statement, use `infino_sql`. |
|
|
313
|
+
| `infino_ask` (with `INFINO_MCP_ASK`) | `question`, `table?`, `tables?`, `k?`, `context?`, `maxWallSecs?` | A plain-language question answered by a retrieval agent on Infino Cloud, which runs the searches and SQL itself and returns the rows it found (`facts`), the statement whose rows answer the question (`statement`) and `coverage`, never a summary. Each ask runs a model loop billed to the account and takes seconds to a few minutes; when you already know the statement, use `infino_sql`. |
|
|
307
314
|
|
|
308
315
|
### Writing data
|
|
309
316
|
|
|
@@ -327,7 +334,7 @@ This server runs locally, beside the client, and keeps data and credentials on t
|
|
|
327
334
|
- **Local execution, no inbound listener.** It runs as a subprocess of your MCP client over stdio and opens no network listener. In the default local/bucket mode it contacts no remote service. When `INFINO_MCP_URI` is a hosted `https://` endpoint, it makes **outbound** TLS calls to that endpoint to serve searches, SQL, and (if enabled) writes — so the data in those requests reaches the hosted service you configured, and nothing else.
|
|
328
335
|
- **No data sent for embedding, by default.** With the default provider, query and document embedding uses a local model, so text is never sent to a third-party embedding API and there is no embedding API key to provision or leak. In hosted mode only the resulting vector, not the text, reaches the Infino Cloud endpoint. If you configure the OpenAI-compatible provider, the text being embedded is sent to the endpoint you name.
|
|
329
336
|
- **Credentials stay in the environment.** Storage credentials (`AWS_*`/`AZURE_*`) and the hosted API key (`INFINO_API_KEY`) are read from environment variables and used only to reach the store or endpoint you configured. They are never logged or returned in tool output.
|
|
330
|
-
- **Who can write is decided outside the server.**
|
|
337
|
+
- **Who can write is decided outside the server.** Every data tool, writes included, is always available to the agent. On Infino Cloud the API key's capabilities bound what the connection may do (a read-scoped key is refused every write). Locally, point the server only at data the agent may change. Every tool carries MCP annotations (`readOnlyHint`, `destructiveHint`) so your client can ask for confirmation on its own terms.
|
|
331
338
|
- **Least privilege.** Point `INFINO_MCP_URI` at the narrowest dataset the task needs, and supply storage credentials scoped to that bucket/prefix.
|
|
332
339
|
|
|
333
340
|
---
|
package/dist/agent-api.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
2
|
// SPDX-FileCopyrightText: Copyright The Infino Authors
|
|
3
3
|
//
|
|
4
|
-
// The Infino Cloud routes the binding does not wrap: the
|
|
5
|
-
// features,
|
|
6
|
-
//
|
|
4
|
+
// The Infino Cloud routes and options the binding does not wrap: the
|
|
5
|
+
// account's switched-on features, a SQL query checked against its question,
|
|
6
|
+
// and the agent routes an account reaches only when its agent APIs are
|
|
7
|
+
// switched on (a table's card, the keys tables join on). Called over plain
|
|
7
8
|
// HTTPS with the same API key the binding uses, and only on a hosted
|
|
8
9
|
// connection; an embedded catalog has none of these.
|
|
9
10
|
/** Split a hosted URI into its service base and database, or `null` when the
|
|
@@ -50,6 +51,27 @@ const CALL_TIMEOUT_MS = 120_000;
|
|
|
50
51
|
/** How long the startup check waits: the server must come up even when the
|
|
51
52
|
* service is slow to answer, and a check that times out reads as off. */
|
|
52
53
|
const FEATURES_TIMEOUT_MS = 10_000;
|
|
54
|
+
/** The search functions whose second argument is a full-text-indexed column:
|
|
55
|
+
* the ones a result can be checked against. `vector_search` searches a
|
|
56
|
+
* vector column and has none. */
|
|
57
|
+
const TEXT_SEARCH_CALL = /\b(?:bm25_search_prefix|bm25_search|hybrid_search|token_match|exact_match)\s*\(\s*'([^']+)'\s*,\s*'([^']+)'/i;
|
|
58
|
+
/** The table and text column the first text search in a read-only statement
|
|
59
|
+
* runs over, or `null` when it runs none (or writes): what its result is
|
|
60
|
+
* checked against. */
|
|
61
|
+
export function searchedTextColumn(sql) {
|
|
62
|
+
if (!/^\s*(?:select|with)\b/i.test(sql))
|
|
63
|
+
return null;
|
|
64
|
+
const m = TEXT_SEARCH_CALL.exec(sql);
|
|
65
|
+
return m ? { table: m[1], column: m[2] } : null;
|
|
66
|
+
}
|
|
67
|
+
/** The service's words when its workers cannot check a result: the query is
|
|
68
|
+
* then sent again without the check. */
|
|
69
|
+
const VALIDATION_UNAVAILABLE = "validation is not available on this deployment";
|
|
70
|
+
/** Whether `err` says the deployment cannot check results, as opposed to a
|
|
71
|
+
* refusal of the statement itself. */
|
|
72
|
+
export function validationUnavailable(err) {
|
|
73
|
+
return err instanceof AgentApiError && err.status === 400 && err.message.includes(VALIDATION_UNAVAILABLE);
|
|
74
|
+
}
|
|
53
75
|
/** The agent-route client for one hosted database. */
|
|
54
76
|
export class AgentApi {
|
|
55
77
|
endpoint;
|
|
@@ -73,6 +95,20 @@ export class AgentApi {
|
|
|
73
95
|
return false;
|
|
74
96
|
return response.agent_apis === true;
|
|
75
97
|
}
|
|
98
|
+
/** Run `sql` and have the service check its rows against the question:
|
|
99
|
+
* any account may ask, and the check's engine work is metered with the
|
|
100
|
+
* query. A GROUP BY over a search function's small top k is refused before
|
|
101
|
+
* it runs (a 400 naming the shapes that rank the whole table). */
|
|
102
|
+
async querySqlValidated(sql, validation) {
|
|
103
|
+
const validate = { table_name: validation.table, field_name: validation.column };
|
|
104
|
+
if (validation.question !== undefined)
|
|
105
|
+
validate.question = validation.question;
|
|
106
|
+
const result = (await this.request("query_sql", this.dataUrl("query_sql"), {
|
|
107
|
+
method: "POST",
|
|
108
|
+
body: JSON.stringify({ query: sql, validate }),
|
|
109
|
+
}));
|
|
110
|
+
return { rows: Array.isArray(result.rows) ? result.rows : [], validation: result.validation ?? {} };
|
|
111
|
+
}
|
|
76
112
|
/** The column entries of `table`'s card whose names match `pattern`, most
|
|
77
113
|
* populated first, as the service's optimizer last described them. */
|
|
78
114
|
async describeColumns(table, lookup) {
|
package/dist/index.js
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
// whoever configured the local path or bucket credentials; how much a client
|
|
27
27
|
// confirms before a destructive call is the client's decision, driven by the
|
|
28
28
|
// tool annotations below. There is no server-side write gate.
|
|
29
|
-
import { mkdirSync } from "node:fs";
|
|
29
|
+
import { mkdirSync, readFileSync } from "node:fs";
|
|
30
30
|
import { homedir } from "node:os";
|
|
31
31
|
import { join } from "node:path";
|
|
32
32
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -35,7 +35,8 @@ import { z } from "zod";
|
|
|
35
35
|
import { connect, IndexSpec } from "@infino-ai/infino";
|
|
36
36
|
import { embed, embedMany, embedderDim, embedderInfo } from "./embedding.js";
|
|
37
37
|
import { errText as translate, guardSql } from "./guards.js";
|
|
38
|
-
import { AgentApi, AgentApiError, hostedEndpoint } from "./agent-api.js";
|
|
38
|
+
import { AgentApi, AgentApiError, hostedEndpoint, searchedTextColumn, validationUnavailable, } from "./agent-api.js";
|
|
39
|
+
import { joinGate, joinRefusal, withoutComments } from "./join-gate.js";
|
|
39
40
|
// --- connection (env-configured, opened once at startup) -------------------
|
|
40
41
|
//
|
|
41
42
|
// The agent never manages connections: the server is pointed at the data via
|
|
@@ -112,6 +113,9 @@ const apiKey = process.env.INFINO_API_KEY;
|
|
|
112
113
|
// Opt into a connect-time probe so bad credentials or an unreachable bucket
|
|
113
114
|
// fail at startup instead of on the first search.
|
|
114
115
|
const validate = ["1", "true", "yes"].includes((process.env.INFINO_MCP_VALIDATE ?? "").toLowerCase());
|
|
116
|
+
// infino_ask runs a model loop billed to the account, so it is offered only
|
|
117
|
+
// when asked for, and only on an account with the agent tools on.
|
|
118
|
+
const askTool = ["1", "true", "yes"].includes((process.env.INFINO_MCP_ASK ?? "").toLowerCase());
|
|
115
119
|
const connectOptions = {};
|
|
116
120
|
if (isHosted) {
|
|
117
121
|
// Hosted (Infino Cloud): authenticate with the API key; the platform owns the
|
|
@@ -314,7 +318,10 @@ async function embedRows(handle, rows, table) {
|
|
|
314
318
|
// Server-level instructions are returned to the client on initialize and shown
|
|
315
319
|
// to the model — the highest-leverage place to position Infino and steer which
|
|
316
320
|
// tool fires when. Kept factual and answer-first (no keyword stuffing).
|
|
317
|
-
|
|
321
|
+
// The version a client is told is the package's own: package.json ships in the
|
|
322
|
+
// npm tarball beside dist/.
|
|
323
|
+
const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
324
|
+
const server = new McpServer({ name: "infino", version }, {
|
|
318
325
|
instructions: "Infino is an embedded retrieval engine for data on object storage: full-text (BM25), vector, " +
|
|
319
326
|
"hybrid, and SQL search over one copy of the data, in-process, with no separate server or managed " +
|
|
320
327
|
"service. Tables are stored as valid Parquet; DuckDB or pyarrow can read the same files. These tools " +
|
|
@@ -767,6 +774,57 @@ server.registerTool("infino_count", {
|
|
|
767
774
|
return fail(`count failed: ${errText(err)}`);
|
|
768
775
|
}
|
|
769
776
|
});
|
|
777
|
+
// --- Infino Cloud: the account's features, asked once at startup -------------
|
|
778
|
+
//
|
|
779
|
+
// Asked before the tools are registered, so the tool list a client sees is
|
|
780
|
+
// fixed for the session. Any failure to ask reads as off: the binding's tools
|
|
781
|
+
// still serve, and the reason goes to stderr.
|
|
782
|
+
// The service's own words for a refusal on a route the binding does not wrap:
|
|
783
|
+
// errText's readings are for the binding's data routes, where a 403 means a
|
|
784
|
+
// key without write.
|
|
785
|
+
const agentErr = (err) => (err instanceof AgentApiError ? err.message : errText(err));
|
|
786
|
+
const endpoint = isHosted ? hostedEndpoint(uri) : null;
|
|
787
|
+
const agentApi = endpoint && apiKey ? new AgentApi(endpoint, apiKey) : null;
|
|
788
|
+
let agentTools = false;
|
|
789
|
+
if (agentApi) {
|
|
790
|
+
try {
|
|
791
|
+
agentTools = await agentApi.agentApisEnabled();
|
|
792
|
+
}
|
|
793
|
+
catch (err) {
|
|
794
|
+
console.error(`Could not ask whether this account has the agent tools (${agentErr(err)}); serving without them.`);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
// The database's tables, for the join check: listed at most once a minute,
|
|
798
|
+
// since a statement may name a table created a moment ago.
|
|
799
|
+
const TABLES_TTL_MS = 60_000;
|
|
800
|
+
let tablesListed = null;
|
|
801
|
+
function knownTables() {
|
|
802
|
+
if (!tablesListed || performance.now() - tablesListed.at > TABLES_TTL_MS) {
|
|
803
|
+
tablesListed = { at: performance.now(), names: db.listTables() };
|
|
804
|
+
}
|
|
805
|
+
return tablesListed.names;
|
|
806
|
+
}
|
|
807
|
+
// The service's keys among a set of tables, asked for once per set for the
|
|
808
|
+
// server's life. A service that cannot answer leaves the statement unchecked
|
|
809
|
+
// rather than unrun - the check is a guard, not a precondition - and says so
|
|
810
|
+
// on stderr.
|
|
811
|
+
const keysAsked = new Map();
|
|
812
|
+
function keysAmong(tables) {
|
|
813
|
+
const set = [...tables].sort().join(",");
|
|
814
|
+
let pending = keysAsked.get(set);
|
|
815
|
+
if (!pending) {
|
|
816
|
+
pending = agentApi
|
|
817
|
+
.joinKeys(tables)
|
|
818
|
+
.then((record) => (record.joins ?? []).filter((j) => typeof j?.predicate === "string"))
|
|
819
|
+
.catch((err) => {
|
|
820
|
+
console.error(`join_keys for ${set} failed; the statement runs unchecked: ${agentErr(err)}`);
|
|
821
|
+
keysAsked.delete(set);
|
|
822
|
+
return [];
|
|
823
|
+
});
|
|
824
|
+
keysAsked.set(set, pending);
|
|
825
|
+
}
|
|
826
|
+
return pending;
|
|
827
|
+
}
|
|
770
828
|
server.registerTool("infino_sql", {
|
|
771
829
|
title: "SQL over Infino",
|
|
772
830
|
annotations: DESTRUCTIVE,
|
|
@@ -778,7 +836,17 @@ server.registerTool("infino_sql", {
|
|
|
778
836
|
'where the vector goes and pass embed:{"name":"query text"} — the server embeds the text and substitutes the ' +
|
|
779
837
|
"vector in. Example: SELECT path, SUM(end_line - start_line + 1) AS lines FROM " +
|
|
780
838
|
"bm25_search('docs','body','error timeout', 300) GROUP BY path ORDER BY lines DESC. " +
|
|
781
|
-
"Any single statement is allowed, DDL/DML included."
|
|
839
|
+
"Any single statement is allowed, DDL/DML included." +
|
|
840
|
+
(agentApi
|
|
841
|
+
? " On Infino Cloud a query that searches a text column has its rows checked against `question`: the " +
|
|
842
|
+
"result's `validation` says whether they answer it, and what the column holds nowhere if not. A GROUP BY " +
|
|
843
|
+
"over a search function with a k under 300 is refused, since its totals rank a share of the top k rather " +
|
|
844
|
+
"than the table."
|
|
845
|
+
: "") +
|
|
846
|
+
(agentTools
|
|
847
|
+
? " A statement that joins tables must join them on a key infino_join_keys found; one that does not is " +
|
|
848
|
+
"refused with the keys."
|
|
849
|
+
: ""),
|
|
782
850
|
inputSchema: {
|
|
783
851
|
query: z
|
|
784
852
|
.string()
|
|
@@ -789,11 +857,42 @@ server.registerTool("infino_sql", {
|
|
|
789
857
|
.describe("Map of placeholder name -> query text. Each text is embedded with the server's embedder and its vector " +
|
|
790
858
|
"is substituted for every {{name}} in the query — required to use vector_search / hybrid_search. " +
|
|
791
859
|
'E.g. {"q":"error timeout"} fills {{q}}.'),
|
|
860
|
+
...(agentApi
|
|
861
|
+
? {
|
|
862
|
+
question: z
|
|
863
|
+
.string()
|
|
864
|
+
.optional()
|
|
865
|
+
.describe("The question these rows are meant to answer, in the words it was asked. Used only to check the " +
|
|
866
|
+
"rows against it; put nothing else here."),
|
|
867
|
+
}
|
|
868
|
+
: {}),
|
|
792
869
|
},
|
|
793
|
-
}, async ({ query, embed: embeds }) => {
|
|
870
|
+
}, async ({ query, embed: embeds, question }) => {
|
|
794
871
|
try {
|
|
795
|
-
const sql = await applyEmbeds(query, embeds);
|
|
796
|
-
const
|
|
872
|
+
const sql = guardSql(await applyEmbeds(query, embeds));
|
|
873
|
+
const code = withoutComments(sql);
|
|
874
|
+
if (agentApi && agentTools) {
|
|
875
|
+
const verdict = await joinGate(code, knownTables(), keysAmong);
|
|
876
|
+
if (verdict.kind === "refuse")
|
|
877
|
+
return fail(joinRefusal("sql", verdict));
|
|
878
|
+
}
|
|
879
|
+
const searched = agentApi ? searchedTextColumn(code) : null;
|
|
880
|
+
if (agentApi && searched) {
|
|
881
|
+
const t0 = performance.now();
|
|
882
|
+
try {
|
|
883
|
+
const { rows, validation } = await agentApi.querySqlValidated(sql, {
|
|
884
|
+
...searched,
|
|
885
|
+
...(question ? { question } : {}),
|
|
886
|
+
});
|
|
887
|
+
return ok({ rows, validation, took_ms: Math.round((performance.now() - t0) * 1000) / 1000 });
|
|
888
|
+
}
|
|
889
|
+
catch (err) {
|
|
890
|
+
if (!validationUnavailable(err))
|
|
891
|
+
return fail(`sql failed: ${agentErr(err)}`);
|
|
892
|
+
// A deployment that cannot check results runs the query unchecked.
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
const { value: rows, tookMs } = timed(() => db.querySql(sql));
|
|
797
896
|
return ok({ rows, took_ms: tookMs });
|
|
798
897
|
}
|
|
799
898
|
catch (err) {
|
|
@@ -877,24 +976,6 @@ server.registerTool("infino_delete_documents", {
|
|
|
877
976
|
}
|
|
878
977
|
});
|
|
879
978
|
// --- agent tools (Infino Cloud accounts with the agent routes on) ----------
|
|
880
|
-
//
|
|
881
|
-
// Asked once at startup, so the tool list a client sees is fixed for the
|
|
882
|
-
// session. Any failure to ask reads as off: the binding's tools still serve,
|
|
883
|
-
// and the reason goes to stderr.
|
|
884
|
-
// The service's own words for an agent route's refusal: errText's readings are
|
|
885
|
-
// for the binding's data routes, where a 403 means a key without write.
|
|
886
|
-
const agentErr = (err) => (err instanceof AgentApiError ? err.message : errText(err));
|
|
887
|
-
const endpoint = isHosted ? hostedEndpoint(uri) : null;
|
|
888
|
-
const agentApi = endpoint && apiKey ? new AgentApi(endpoint, apiKey) : null;
|
|
889
|
-
let agentTools = false;
|
|
890
|
-
if (agentApi) {
|
|
891
|
-
try {
|
|
892
|
-
agentTools = await agentApi.agentApisEnabled();
|
|
893
|
-
}
|
|
894
|
-
catch (err) {
|
|
895
|
-
console.error(`Could not ask whether this account has the agent tools (${agentErr(err)}); serving without them.`);
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
979
|
if (agentApi && agentTools) {
|
|
899
980
|
server.registerTool("infino_describe_columns", {
|
|
900
981
|
title: "A table's column entries, by name or name family",
|
|
@@ -949,55 +1030,57 @@ if (agentApi && agentTools) {
|
|
|
949
1030
|
return fail(`join_keys failed: ${agentErr(err)}`);
|
|
950
1031
|
}
|
|
951
1032
|
});
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
"
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1033
|
+
if (askTool) {
|
|
1034
|
+
server.registerTool("infino_ask", {
|
|
1035
|
+
title: "Ask a question of the data: one retrieval, the rows back",
|
|
1036
|
+
annotations: READ_ONLY,
|
|
1037
|
+
description: "Ask a question about this database in plain language. A retrieval agent on Infino Cloud reads the " +
|
|
1038
|
+
"tables' cards, chooses and runs the searches and SQL itself (joins included), checks the result " +
|
|
1039
|
+
"against the question, and returns the rows it found (`facts`), the statement whose rows answer the " +
|
|
1040
|
+
"question (`statement`), and how many rows that statement returned (`coverage`). It never writes a " +
|
|
1041
|
+
"summary: read the rows, and reuse `statement` with infino_sql to go further. Use it for any question " +
|
|
1042
|
+
"that is not one statement you already know how to write: where a value lives, which column holds a " +
|
|
1043
|
+
"name, counts and rankings across tables. Several asks in one reply run at the same time. When the " +
|
|
1044
|
+
"database holds several tables and the question is about one or a few, name them in `table` or " +
|
|
1045
|
+
"`tables`. Each ask runs a model loop on the service: it takes seconds to a few minutes and its model " +
|
|
1046
|
+
"calls are billed to the account, so when you already know the statement, run it with infino_sql " +
|
|
1047
|
+
"instead. A loop that found no answer still returns, with `terminate` saying why; if an ask comes back " +
|
|
1048
|
+
"thin, rephrase it, narrower or broader, and ask again.",
|
|
1049
|
+
inputSchema: {
|
|
1050
|
+
question: z
|
|
1051
|
+
.string()
|
|
1052
|
+
.min(1)
|
|
1053
|
+
.describe("The question, about the data, in plain language. Its names, numbers and quoted terms are what " +
|
|
1054
|
+
"the result is checked for, so put only the question here."),
|
|
1055
|
+
table: z.string().min(1).optional().describe("The one table the question is about."),
|
|
1056
|
+
tables: z
|
|
1057
|
+
.array(z.string().min(1))
|
|
1058
|
+
.min(1)
|
|
1059
|
+
.max(8)
|
|
1060
|
+
.optional()
|
|
1061
|
+
.describe("The few tables the question is about, which the agent may join."),
|
|
1062
|
+
k: z.number().int().min(1).max(1000).optional().describe("Rows to return at most (default 10)."),
|
|
1063
|
+
context: z
|
|
1064
|
+
.string()
|
|
1065
|
+
.optional()
|
|
1066
|
+
.describe("Anything the agent should know beside the question (a convention, a definition); not checked for."),
|
|
1067
|
+
maxWallSecs: z
|
|
1068
|
+
.number()
|
|
1069
|
+
.int()
|
|
1070
|
+
.min(10)
|
|
1071
|
+
.max(600)
|
|
1072
|
+
.optional()
|
|
1073
|
+
.describe("A shorter time budget in seconds than the service's own, for a cheaper, faster ask."),
|
|
1074
|
+
},
|
|
1075
|
+
}, async (request) => {
|
|
1076
|
+
try {
|
|
1077
|
+
return ok(await agentApi.ask(request));
|
|
1078
|
+
}
|
|
1079
|
+
catch (err) {
|
|
1080
|
+
return fail(`ask failed: ${agentErr(err)}`);
|
|
1081
|
+
}
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1001
1084
|
}
|
|
1002
1085
|
// --- transport -------------------------------------------------------------
|
|
1003
1086
|
// stdio for desktop/CLI clients (Claude Desktop/Code, Cursor). Logs go to
|
|
@@ -1005,4 +1088,5 @@ if (agentApi && agentTools) {
|
|
|
1005
1088
|
const transport = new StdioServerTransport();
|
|
1006
1089
|
await server.connect(transport);
|
|
1007
1090
|
console.error(`infino MCP server ready on stdio (uri: ${uri}, mode: ${isHosted ? "hosted" : "embedded"}, ` +
|
|
1008
|
-
`embedder: ${embedderInfo()}, agent tools: ${agentTools ? "on" : "off"}
|
|
1091
|
+
`embedder: ${embedderInfo()}, agent tools: ${agentTools ? "on" : "off"}, ` +
|
|
1092
|
+
`ask: ${agentTools && askTool ? "on" : "off"})`);
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// SPDX-FileCopyrightText: Copyright The Infino Authors
|
|
3
|
+
//
|
|
4
|
+
// The check a statement across tables passes before infino_sql runs it, on an
|
|
5
|
+
// Infino Cloud account with the agent tools on: the service's `join_keys`
|
|
6
|
+
// says which columns the tables join on, found on their values, and a
|
|
7
|
+
// statement that joins two or more tables without one of those keys in it is
|
|
8
|
+
// refused with the keys, so the model rewrites it on a key that holds instead
|
|
9
|
+
// of one whose column names merely read well.
|
|
10
|
+
//
|
|
11
|
+
// A model asked a question that needs two tables joined tends to match
|
|
12
|
+
// columns by name and never call infino_join_keys, though the tool is there
|
|
13
|
+
// and its text says to call it first. The keys therefore reach the model in
|
|
14
|
+
// the refusal of a statement it already wrote without them.
|
|
15
|
+
/** Words that follow a table name in a statement and are not its alias. */
|
|
16
|
+
const NOT_AN_ALIAS = new Set([
|
|
17
|
+
"on",
|
|
18
|
+
"where",
|
|
19
|
+
"join",
|
|
20
|
+
"inner",
|
|
21
|
+
"left",
|
|
22
|
+
"right",
|
|
23
|
+
"full",
|
|
24
|
+
"cross",
|
|
25
|
+
"outer",
|
|
26
|
+
"natural",
|
|
27
|
+
"using",
|
|
28
|
+
"group",
|
|
29
|
+
"order",
|
|
30
|
+
"limit",
|
|
31
|
+
"offset",
|
|
32
|
+
"having",
|
|
33
|
+
"union",
|
|
34
|
+
"except",
|
|
35
|
+
"intersect",
|
|
36
|
+
"and",
|
|
37
|
+
"or",
|
|
38
|
+
"not",
|
|
39
|
+
"as",
|
|
40
|
+
"set",
|
|
41
|
+
"window",
|
|
42
|
+
"qualify",
|
|
43
|
+
"fetch",
|
|
44
|
+
"for",
|
|
45
|
+
"with",
|
|
46
|
+
"select",
|
|
47
|
+
"from",
|
|
48
|
+
"values",
|
|
49
|
+
"returning",
|
|
50
|
+
"lateral",
|
|
51
|
+
"tablesample",
|
|
52
|
+
]);
|
|
53
|
+
/** The table-valued search functions whose first argument names a table
|
|
54
|
+
* and whose result is aliased as that table's rows. */
|
|
55
|
+
const SEARCH_FUNCTIONS = [
|
|
56
|
+
"hybrid_search",
|
|
57
|
+
"bm25_search",
|
|
58
|
+
"bm25_search_prefix",
|
|
59
|
+
"vector_search",
|
|
60
|
+
"token_match",
|
|
61
|
+
"exact_match",
|
|
62
|
+
];
|
|
63
|
+
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
64
|
+
/** The graph functions: `graph_walk('<table>', '<seed table>', [ids], hops, k)`
|
|
65
|
+
* and `graph_rank(...)` name two tables in their arguments and join nothing -
|
|
66
|
+
* the walk is the service's, over the keys it verified - so the tables named
|
|
67
|
+
* there are not a statement spanning tables. */
|
|
68
|
+
const GRAPH_FUNCTIONS = ["graph_walk", "graph_rank"];
|
|
69
|
+
/** `query` with every graph function's argument list blanked, so the tables
|
|
70
|
+
* it names are not read as a JOIN the gate must hold to a key. */
|
|
71
|
+
export function withoutGraphCalls(query) {
|
|
72
|
+
return query.replace(new RegExp(`\\b(?:${GRAPH_FUNCTIONS.join("|")})\\s*\\([^)]*\\)`, "gi"), (call) => call.replace(/[^()]/g, " "));
|
|
73
|
+
}
|
|
74
|
+
/** `query` without its comments: a table or a join named in one is not in
|
|
75
|
+
* the statement. Quoted text is kept as it is. */
|
|
76
|
+
export function withoutComments(query) {
|
|
77
|
+
let out = "";
|
|
78
|
+
for (let i = 0; i < query.length;) {
|
|
79
|
+
const c = query[i];
|
|
80
|
+
if (c === "'" || c === '"') {
|
|
81
|
+
const close = query.indexOf(c, i + 1);
|
|
82
|
+
const end = close < 0 ? query.length : close + 1;
|
|
83
|
+
out += query.slice(i, end);
|
|
84
|
+
i = end;
|
|
85
|
+
}
|
|
86
|
+
else if (c === "-" && query[i + 1] === "-") {
|
|
87
|
+
const nl = query.indexOf("\n", i);
|
|
88
|
+
i = nl < 0 ? query.length : nl;
|
|
89
|
+
}
|
|
90
|
+
else if (c === "/" && query[i + 1] === "*") {
|
|
91
|
+
const close = query.indexOf("*/", i + 2);
|
|
92
|
+
out += " ";
|
|
93
|
+
i = close < 0 ? query.length : close + 2;
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
out += c;
|
|
97
|
+
i += 1;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
/** The known tables a statement names, as identifiers or as the string
|
|
103
|
+
* argument of a search function, each once in the order given. */
|
|
104
|
+
export function tablesNamed(query, tables) {
|
|
105
|
+
const named = [];
|
|
106
|
+
for (const table of tables) {
|
|
107
|
+
if (!table)
|
|
108
|
+
continue;
|
|
109
|
+
const re = new RegExp(`(?<![\\w.])${escapeRegex(table)}(?![\\w])`, "i");
|
|
110
|
+
if (re.test(query) && !named.includes(table))
|
|
111
|
+
named.push(table);
|
|
112
|
+
}
|
|
113
|
+
return named;
|
|
114
|
+
}
|
|
115
|
+
/** Every alias a statement gives one of `tables`: `FROM issues i`,
|
|
116
|
+
* `JOIN logs AS l`, `hybrid_search('chunks', ...) AS c`. Alias to table. */
|
|
117
|
+
export function aliasesOf(query, tables) {
|
|
118
|
+
const aliases = new Map();
|
|
119
|
+
for (const table of tables) {
|
|
120
|
+
const plain = new RegExp(`(?<![\\w.'"])${escapeRegex(table)}(?![\\w])\\s+(?:as\\s+)?([A-Za-z_]\\w*)`, "gi");
|
|
121
|
+
for (const m of query.matchAll(plain)) {
|
|
122
|
+
const alias = m[1];
|
|
123
|
+
if (!NOT_AN_ALIAS.has(alias.toLowerCase()) && alias.toLowerCase() !== table.toLowerCase())
|
|
124
|
+
aliases.set(alias.toLowerCase(), table);
|
|
125
|
+
}
|
|
126
|
+
const searched = new RegExp(`(?:${SEARCH_FUNCTIONS.join("|")})\\(\\s*'${escapeRegex(table)}'[^)]*\\)\\s+(?:as\\s+)?([A-Za-z_]\\w*)`, "gi");
|
|
127
|
+
for (const m of query.matchAll(searched)) {
|
|
128
|
+
const alias = m[1];
|
|
129
|
+
if (!NOT_AN_ALIAS.has(alias.toLowerCase()) && alias.toLowerCase() !== table.toLowerCase())
|
|
130
|
+
aliases.set(alias.toLowerCase(), table);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// A subquery or a CTE over one table stands for that table: its alias,
|
|
134
|
+
// the CTE's name and any alias given the CTE are the table's. A join
|
|
135
|
+
// written between two of them (each table grouped in a subquery, then the
|
|
136
|
+
// two joined on their key) was refused before, its `e.id = c.id` naming no
|
|
137
|
+
// table the check knew. A subquery or CTE over several tables stands for
|
|
138
|
+
// none: the join inside it is held to a key on its own.
|
|
139
|
+
for (const [name, table] of derivedTables(query, tables)) {
|
|
140
|
+
if (!aliases.has(name))
|
|
141
|
+
aliases.set(name, table);
|
|
142
|
+
}
|
|
143
|
+
return aliases;
|
|
144
|
+
}
|
|
145
|
+
/** The single known table each subquery alias and CTE name of a statement
|
|
146
|
+
* reads, and each alias given such a CTE (`FROM recent r`). Names in
|
|
147
|
+
* lowercase. */
|
|
148
|
+
function derivedTables(query, tables) {
|
|
149
|
+
const derived = new Map();
|
|
150
|
+
const only = (inner) => {
|
|
151
|
+
const named = tablesNamed(inner, tables);
|
|
152
|
+
return named.length === 1 ? named[0] : null;
|
|
153
|
+
};
|
|
154
|
+
const ctes = new Map();
|
|
155
|
+
for (const m of query.matchAll(CTE_START)) {
|
|
156
|
+
const open = (m.index ?? 0) + m[0].length - 1;
|
|
157
|
+
const inner = query.slice(open + 1, groupEnd(query, open) - 1);
|
|
158
|
+
const table = only(inner);
|
|
159
|
+
if (table)
|
|
160
|
+
ctes.set(m[1].toLowerCase(), { table, inner });
|
|
161
|
+
}
|
|
162
|
+
for (let i = 0; i < query.length; i++) {
|
|
163
|
+
const c = query[i];
|
|
164
|
+
if (c === "'" || c === '"') {
|
|
165
|
+
const close = query.indexOf(c, i + 1);
|
|
166
|
+
i = close < 0 ? query.length : close;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (c !== "(")
|
|
170
|
+
continue;
|
|
171
|
+
const end = groupEnd(query, i);
|
|
172
|
+
const inner = query.slice(i + 1, end - 1);
|
|
173
|
+
if (!SUBQUERY_START.test(inner))
|
|
174
|
+
continue;
|
|
175
|
+
const alias = /^\s*(?:as\s+)?([A-Za-z_]\w*)/i.exec(query.slice(end))?.[1];
|
|
176
|
+
const table = only(inner);
|
|
177
|
+
if (alias &&
|
|
178
|
+
table &&
|
|
179
|
+
!NOT_AN_ALIAS.has(alias.toLowerCase()) &&
|
|
180
|
+
carriesAsSelected(query, [alias], inner)) {
|
|
181
|
+
derived.set(alias.toLowerCase(), table);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
for (const [cte, { table, inner }] of ctes) {
|
|
185
|
+
const names = [cte];
|
|
186
|
+
const aliased = new RegExp(`(?<![\\w.'"])${escapeRegex(cte)}(?![\\w])\\s+(?:as\\s+)?([A-Za-z_]\\w*)`, "gi");
|
|
187
|
+
for (const m of query.matchAll(aliased)) {
|
|
188
|
+
const alias = m[1].toLowerCase();
|
|
189
|
+
if (!NOT_AN_ALIAS.has(alias) && alias !== cte)
|
|
190
|
+
names.push(alias);
|
|
191
|
+
}
|
|
192
|
+
// The CTE stands for its table under every name only when what the
|
|
193
|
+
// statement compares through those names is the table's own columns.
|
|
194
|
+
if (!carriesAsSelected(query, names, inner))
|
|
195
|
+
continue;
|
|
196
|
+
for (const name of names)
|
|
197
|
+
derived.set(name, table);
|
|
198
|
+
}
|
|
199
|
+
return derived;
|
|
200
|
+
}
|
|
201
|
+
/** Whether every column `query` compares through `names` (`n.col = ...`) is
|
|
202
|
+
* one the subquery or CTE `inner` selects under its own name - `col`,
|
|
203
|
+
* `t.col`, `col AS col` - or `inner` selects `*`. A column renamed inside
|
|
204
|
+
* (`account AS id`) is not the table's column of that name, so a derived
|
|
205
|
+
* name that compares one does not stand for the table: the join written
|
|
206
|
+
* through it is held to a key as a join between unknown sources would be.
|
|
207
|
+
* Columns only selected or sorted on join nothing and are left alone. */
|
|
208
|
+
function carriesAsSelected(query, names, inner) {
|
|
209
|
+
const selected = selectedAsThemselves(inner);
|
|
210
|
+
if (selected === "all")
|
|
211
|
+
return true;
|
|
212
|
+
for (const name of names) {
|
|
213
|
+
const read = new RegExp(`(?<![\\w.'"])"?${escapeRegex(name)}"?\\s*\\.\\s*"?([A-Za-z_]\\w*)"?`, "gi");
|
|
214
|
+
for (const m of query.matchAll(read)) {
|
|
215
|
+
const at = m.index ?? 0;
|
|
216
|
+
const compared = /=\s*$/.test(query.slice(0, at)) || /^\s*=/.test(query.slice(at + m[0].length));
|
|
217
|
+
if (compared && !selected.has(m[1].toLowerCase()))
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
223
|
+
/** The columns a query's top-level select list carries under their own
|
|
224
|
+
* names, lowercase: `col`, `t.col` and `col AS col`, quoted or not; "all"
|
|
225
|
+
* when the list holds `*` or `t.*`. An expression or a renamed column
|
|
226
|
+
* carries nothing. */
|
|
227
|
+
function selectedAsThemselves(inner) {
|
|
228
|
+
const carried = new Set();
|
|
229
|
+
for (const item of topLevelSelectList(inner)) {
|
|
230
|
+
const text = item.trim();
|
|
231
|
+
if (/^(?:"?[A-Za-z_]\w*"?\s*\.\s*)?\*$/.test(text))
|
|
232
|
+
return "all";
|
|
233
|
+
const m = /^(?:"?[A-Za-z_]\w*"?\s*\.\s*)?"?([A-Za-z_]\w*)"?(?:\s+(?:as\s+)?"?([A-Za-z_]\w*)"?)?$/i.exec(text);
|
|
234
|
+
if (!m)
|
|
235
|
+
continue;
|
|
236
|
+
const column = m[1].toLowerCase();
|
|
237
|
+
if (column === (m[2] ?? m[1]).toLowerCase())
|
|
238
|
+
carried.add(column);
|
|
239
|
+
}
|
|
240
|
+
return carried;
|
|
241
|
+
}
|
|
242
|
+
/** The items of a query's first top-level select list: what lies between
|
|
243
|
+
* its SELECT (and any DISTINCT) and the FROM at the same depth, split at the
|
|
244
|
+
* commas at that depth. Empty when the query has no such list. */
|
|
245
|
+
function topLevelSelectList(query) {
|
|
246
|
+
const start = /^\s*select\s+(?:distinct\s+)?/i.exec(query);
|
|
247
|
+
if (!start)
|
|
248
|
+
return [];
|
|
249
|
+
const items = [];
|
|
250
|
+
let depth = 0;
|
|
251
|
+
let from = start[0].length;
|
|
252
|
+
for (let i = from; i < query.length; i++) {
|
|
253
|
+
const c = query[i];
|
|
254
|
+
if (c === "'" || c === '"') {
|
|
255
|
+
const close = query.indexOf(c, i + 1);
|
|
256
|
+
i = close < 0 ? query.length : close;
|
|
257
|
+
}
|
|
258
|
+
else if (c === "(")
|
|
259
|
+
depth += 1;
|
|
260
|
+
else if (c === ")")
|
|
261
|
+
depth -= 1;
|
|
262
|
+
else if (depth === 0 && c === ",") {
|
|
263
|
+
items.push(query.slice(from, i));
|
|
264
|
+
from = i + 1;
|
|
265
|
+
}
|
|
266
|
+
else if (depth === 0 && /\s/.test(c) && /^\s+from\b/i.test(query.slice(i))) {
|
|
267
|
+
items.push(query.slice(from, i));
|
|
268
|
+
return items;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
items.push(query.slice(from));
|
|
272
|
+
return items;
|
|
273
|
+
}
|
|
274
|
+
/** A statement or predicate reduced to what its join condition is made of:
|
|
275
|
+
* lowercase, aliases replaced by their tables, quotes and blanks gone. */
|
|
276
|
+
export function normalizeSql(text, aliases) {
|
|
277
|
+
let out = text.toLowerCase();
|
|
278
|
+
for (const [alias, table] of aliases) {
|
|
279
|
+
out = out.replace(new RegExp(`(?<![\\w.])${escapeRegex(alias)}\\.`, "g"), `${table.toLowerCase()}.`);
|
|
280
|
+
}
|
|
281
|
+
return out.replace(/["`]/g, "").replace(/\s+/g, "");
|
|
282
|
+
}
|
|
283
|
+
/** Whether `predicate` (`a.x = b.y`, either side possibly an expression) is
|
|
284
|
+
* written in the statement, either way round. */
|
|
285
|
+
export function predicateHolds(query, predicate, aliases) {
|
|
286
|
+
const statement = normalizeSql(query, aliases);
|
|
287
|
+
const sides = predicate.split(/\s=\s/);
|
|
288
|
+
if (sides.length !== 2)
|
|
289
|
+
return statement.includes(normalizeSql(predicate, aliases));
|
|
290
|
+
const [l, r] = sides.map((s) => normalizeSql(s, aliases));
|
|
291
|
+
return statement.includes(`${l}=${r}`) || statement.includes(`${r}=${l}`);
|
|
292
|
+
}
|
|
293
|
+
/** The set operators that put one query's rows after another's: the
|
|
294
|
+
* branches they separate join nothing to each other. */
|
|
295
|
+
const SET_OPERATOR = /\b(?:union(?:\s+all)?|intersect|except)\b/gi;
|
|
296
|
+
/** The opening of a subquery inside parentheses. */
|
|
297
|
+
const SUBQUERY_START = /^\s*(?:select|with)\b/i;
|
|
298
|
+
/** A CTE's name and the parenthesis its query opens with: `WITH r AS (`,
|
|
299
|
+
* `, s AS (`. */
|
|
300
|
+
const CTE_START = /(?:\bwith\s+(?:recursive\s+)?|,\s*)([A-Za-z_]\w*)\s+as\s*\(/gi;
|
|
301
|
+
/** A FROM list that names several sources (`FROM a, b`): a join. */
|
|
302
|
+
const FROM_LIST = /\bfrom\b([\s\S]*?)(?:\bwhere\b|\bgroup\b|\border\b|\blimit\b|\bhaving\b|\bwindow\b|\bqualify\b|$)/gi;
|
|
303
|
+
/** The index just past the parenthesised group that opens at `open`, quotes
|
|
304
|
+
* skipped; the text's end when the group is never closed. */
|
|
305
|
+
function groupEnd(text, open) {
|
|
306
|
+
let depth = 0;
|
|
307
|
+
for (let i = open; i < text.length; i++) {
|
|
308
|
+
const c = text[i];
|
|
309
|
+
if (c === "'" || c === '"') {
|
|
310
|
+
const close = text.indexOf(c, i + 1);
|
|
311
|
+
i = close < 0 ? text.length : close;
|
|
312
|
+
}
|
|
313
|
+
else if (c === "(")
|
|
314
|
+
depth += 1;
|
|
315
|
+
else if (c === ")" && --depth === 0)
|
|
316
|
+
return i + 1;
|
|
317
|
+
}
|
|
318
|
+
return text.length;
|
|
319
|
+
}
|
|
320
|
+
/** A quoted text that can name a table: one identifier, as a search
|
|
321
|
+
* function's first argument does (`'chunks'`). Any other quoted text is a
|
|
322
|
+
* value, whatever words it holds. */
|
|
323
|
+
const QUOTED_NAME = /^['"][A-Za-z_]\w*['"]$/;
|
|
324
|
+
/** `text` with its subqueries taken out and blanked, and the subqueries
|
|
325
|
+
* themselves, at whatever depth they sit (inside a function call's
|
|
326
|
+
* arguments too). A parenthesised group that is not a query - a function's
|
|
327
|
+
* arguments, a search function's table - stays in place; a quoted value is
|
|
328
|
+
* blanked, a quoted name kept. */
|
|
329
|
+
function splitSubqueries(text) {
|
|
330
|
+
let outer = "";
|
|
331
|
+
const subqueries = [];
|
|
332
|
+
for (let i = 0; i < text.length;) {
|
|
333
|
+
const c = text[i];
|
|
334
|
+
if (c === "'" || c === '"') {
|
|
335
|
+
const close = text.indexOf(c, i + 1);
|
|
336
|
+
const end = close < 0 ? text.length : close + 1;
|
|
337
|
+
const quoted = text.slice(i, end);
|
|
338
|
+
outer += QUOTED_NAME.test(quoted) ? quoted : " ".repeat(quoted.length);
|
|
339
|
+
i = end;
|
|
340
|
+
}
|
|
341
|
+
else if (c === "(") {
|
|
342
|
+
const end = groupEnd(text, i);
|
|
343
|
+
const inner = text.slice(i + 1, Math.max(i + 1, end - 1));
|
|
344
|
+
if (SUBQUERY_START.test(inner)) {
|
|
345
|
+
subqueries.push(inner);
|
|
346
|
+
outer += " ".repeat(end - i);
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
const nested = splitSubqueries(inner);
|
|
350
|
+
outer += `(${nested.outer})`;
|
|
351
|
+
subqueries.push(...nested.subqueries);
|
|
352
|
+
}
|
|
353
|
+
i = end;
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
outer += c;
|
|
357
|
+
i += 1;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return { outer, subqueries };
|
|
361
|
+
}
|
|
362
|
+
/** `text` cut at its set operators outside parentheses and quotes. */
|
|
363
|
+
function setBranches(text) {
|
|
364
|
+
const { outer } = splitSubqueries(text);
|
|
365
|
+
const cuts = [];
|
|
366
|
+
for (const m of outer.matchAll(SET_OPERATOR))
|
|
367
|
+
cuts.push(m.index ?? 0, (m.index ?? 0) + m[0].length);
|
|
368
|
+
const branches = [];
|
|
369
|
+
let from = 0;
|
|
370
|
+
for (let k = 0; k < cuts.length; k += 2) {
|
|
371
|
+
branches.push(text.slice(from, cuts[k]));
|
|
372
|
+
from = cuts[k + 1];
|
|
373
|
+
}
|
|
374
|
+
branches.push(text.slice(from));
|
|
375
|
+
return branches;
|
|
376
|
+
}
|
|
377
|
+
/** Whether a statement joins known tables, so that its rows pair one
|
|
378
|
+
* table's with another's and the pairing must be on a key the data holds:
|
|
379
|
+
* two tables in one query's FROM or JOIN; a subquery over another table
|
|
380
|
+
* than the query around it (`IN (SELECT ... FROM b)`, a correlated
|
|
381
|
+
* subquery); or queries over different tables joined to each other (CTEs
|
|
382
|
+
* JOINed, or listed in one FROM). Queries that only sit side by side join
|
|
383
|
+
* nothing and run as written: the branches of a UNION, INTERSECT or EXCEPT
|
|
384
|
+
* (a count per table, say), and subqueries over one table each in a SELECT
|
|
385
|
+
* list with no table of its own. */
|
|
386
|
+
export function joinsTables(query, known) {
|
|
387
|
+
for (const branch of setBranches(query)) {
|
|
388
|
+
const { outer, subqueries } = splitSubqueries(branch);
|
|
389
|
+
const own = tablesNamed(outer, known);
|
|
390
|
+
if (own.length >= 2)
|
|
391
|
+
return true;
|
|
392
|
+
if (subqueries.some((sub) => joinsTables(sub, known)))
|
|
393
|
+
return true;
|
|
394
|
+
const below = [...new Set(subqueries.flatMap((sub) => tablesNamed(sub, known)))];
|
|
395
|
+
if (own.length === 1 && below.some((table) => table !== own[0]))
|
|
396
|
+
return true;
|
|
397
|
+
if (own.length === 0 && below.length >= 2) {
|
|
398
|
+
const joined = /\bjoin\b/i.test(outer) || [...outer.matchAll(FROM_LIST)].some((m) => m[1].includes(","));
|
|
399
|
+
if (joined)
|
|
400
|
+
return true;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return false;
|
|
404
|
+
}
|
|
405
|
+
/** The gate. `known` is every table the statement may name; `keys` fetches
|
|
406
|
+
* the service's joins among the named tables and is called only when the
|
|
407
|
+
* statement joins two or more of them (`joinsTables`). Pass the statement
|
|
408
|
+
* without its comments (`withoutComments`). */
|
|
409
|
+
export async function joinGate(query, known, keys) {
|
|
410
|
+
const unwalked = withoutGraphCalls(query);
|
|
411
|
+
const tables = tablesNamed(unwalked, known);
|
|
412
|
+
if (tables.length < 2)
|
|
413
|
+
return { kind: "run", tables, keysAsked: false };
|
|
414
|
+
if (!joinsTables(unwalked, known))
|
|
415
|
+
return { kind: "run", tables, keysAsked: false };
|
|
416
|
+
const joins = (await keys(tables)).filter((j) => tables.includes(j.from_table) && tables.includes(j.to_table));
|
|
417
|
+
// Two tables the service found no key between: nothing to hold the
|
|
418
|
+
// statement to; it runs as written.
|
|
419
|
+
if (joins.length === 0)
|
|
420
|
+
return { kind: "run", tables, keysAsked: true };
|
|
421
|
+
const aliases = aliasesOf(query, tables);
|
|
422
|
+
if (joins.some((j) => predicateHolds(query, j.predicate, aliases)))
|
|
423
|
+
return { kind: "run", tables, keysAsked: true };
|
|
424
|
+
return { kind: "refuse", tables, keys: joins };
|
|
425
|
+
}
|
|
426
|
+
/** The refusal's text: what was spanned, what joins it, what to do. */
|
|
427
|
+
export function joinRefusal(tool, verdict) {
|
|
428
|
+
const list = verdict.keys.map((j) => ` ${j.predicate}`).join("\n");
|
|
429
|
+
return (`${tool} refused: the statement spans ${verdict.tables.join(", ")} without a key Infino Cloud found on their ` +
|
|
430
|
+
`values. infino_join_keys says they join on:\n${list}\nRewrite the statement with one of these as its ON (or ` +
|
|
431
|
+
"WHERE) condition and run it again; a subquery or a condition on other columns is not a join the data supports.");
|
|
432
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@infino-ai/mcp-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.0",
|
|
4
4
|
"description": "MCP server for Infino — keyword, semantic, hybrid, and SQL retrieval for AI agents: RAG, persistent agent memory, and search over data stored as plain Parquet on object storage. Local embeddings, no API key.",
|
|
5
5
|
"mcpName": "io.github.infino-ai/mcp-server",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -58,17 +58,17 @@
|
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"@huggingface/transformers": "^4.3.2",
|
|
61
|
-
"@infino-ai/infino": "^0.11.
|
|
61
|
+
"@infino-ai/infino": "^0.11.27",
|
|
62
62
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
63
63
|
"zod": "^4.6.5"
|
|
64
64
|
},
|
|
65
65
|
"devDependencies": {
|
|
66
66
|
"@eslint/js": "^10.0.1",
|
|
67
67
|
"@types/node": "^26",
|
|
68
|
-
"eslint": "^10.
|
|
68
|
+
"eslint": "^10.15.0",
|
|
69
69
|
"globals": "^17.14.0",
|
|
70
|
-
"prettier": "^3.
|
|
70
|
+
"prettier": "^3.10.1",
|
|
71
71
|
"typescript": "^6.0.3",
|
|
72
|
-
"typescript-eslint": "^8.72.
|
|
72
|
+
"typescript-eslint": "^8.72.2"
|
|
73
73
|
}
|
|
74
74
|
}
|