@infino-ai/mcp-server 0.18.0 → 0.19.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 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
 
@@ -281,7 +281,7 @@ the data.
281
281
  | `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
282
  | `infino_exact_match` | `table`, `value`, `column?`, `limit?` | Unranked exact-equality filter over an indexed column (tag, status, id string). |
283
283
  | `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. |
284
+ | `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
285
  | `infino_list_tables` | — | List the tables in the connected catalog. |
286
286
  | `infino_describe_table` | `table` | Column names and types for a table. |
287
287
  | `infino_create_database` | — | Provision the database the connection names (Infino Cloud); a no-op success locally. Idempotent. |
@@ -295,6 +295,12 @@ Search hits return **full column values** — the `columns` argument is a projec
295
295
 
296
296
  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
297
 
298
+ ### Checked SQL (Infino Cloud)
299
+
300
+ 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.
301
+
302
+ 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.
303
+
298
304
  ### Agent tools (Infino Cloud)
299
305
 
300
306
  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, three more tools appear; otherwise, and on every local or bucket connection, they are not offered at all.
@@ -327,7 +333,7 @@ This server runs locally, beside the client, and keeps data and credentials on t
327
333
  - **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
334
  - **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
335
  - **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.** The full toolset, 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.
336
+ - **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
337
  - **Least privilege.** Point `INFINO_MCP_URI` at the narrowest dataset the task needs, and supply storage credentials scoped to that bucket/prefix.
332
338
 
333
339
  ---
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 account's switched-on
5
- // features, and the agent routes an account reaches only when its agent APIs
6
- // are switched on (a table's card, the keys tables join on). Called over plain
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
@@ -314,7 +315,10 @@ async function embedRows(handle, rows, table) {
314
315
  // Server-level instructions are returned to the client on initialize and shown
315
316
  // to the model — the highest-leverage place to position Infino and steer which
316
317
  // tool fires when. Kept factual and answer-first (no keyword stuffing).
317
- const server = new McpServer({ name: "infino", version: "0.1.0" }, {
318
+ // The version a client is told is the package's own: package.json ships in the
319
+ // npm tarball beside dist/.
320
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
321
+ const server = new McpServer({ name: "infino", version }, {
318
322
  instructions: "Infino is an embedded retrieval engine for data on object storage: full-text (BM25), vector, " +
319
323
  "hybrid, and SQL search over one copy of the data, in-process, with no separate server or managed " +
320
324
  "service. Tables are stored as valid Parquet; DuckDB or pyarrow can read the same files. These tools " +
@@ -767,6 +771,57 @@ server.registerTool("infino_count", {
767
771
  return fail(`count failed: ${errText(err)}`);
768
772
  }
769
773
  });
774
+ // --- Infino Cloud: the account's features, asked once at startup -------------
775
+ //
776
+ // Asked before the tools are registered, so the tool list a client sees is
777
+ // fixed for the session. Any failure to ask reads as off: the binding's tools
778
+ // still serve, and the reason goes to stderr.
779
+ // The service's own words for a refusal on a route the binding does not wrap:
780
+ // errText's readings are for the binding's data routes, where a 403 means a
781
+ // key without write.
782
+ const agentErr = (err) => (err instanceof AgentApiError ? err.message : errText(err));
783
+ const endpoint = isHosted ? hostedEndpoint(uri) : null;
784
+ const agentApi = endpoint && apiKey ? new AgentApi(endpoint, apiKey) : null;
785
+ let agentTools = false;
786
+ if (agentApi) {
787
+ try {
788
+ agentTools = await agentApi.agentApisEnabled();
789
+ }
790
+ catch (err) {
791
+ console.error(`Could not ask whether this account has the agent tools (${agentErr(err)}); serving without them.`);
792
+ }
793
+ }
794
+ // The database's tables, for the join check: listed at most once a minute,
795
+ // since a statement may name a table created a moment ago.
796
+ const TABLES_TTL_MS = 60_000;
797
+ let tablesListed = null;
798
+ function knownTables() {
799
+ if (!tablesListed || performance.now() - tablesListed.at > TABLES_TTL_MS) {
800
+ tablesListed = { at: performance.now(), names: db.listTables() };
801
+ }
802
+ return tablesListed.names;
803
+ }
804
+ // The service's keys among a set of tables, asked for once per set for the
805
+ // server's life. A service that cannot answer leaves the statement unchecked
806
+ // rather than unrun - the check is a guard, not a precondition - and says so
807
+ // on stderr.
808
+ const keysAsked = new Map();
809
+ function keysAmong(tables) {
810
+ const set = [...tables].sort().join(",");
811
+ let pending = keysAsked.get(set);
812
+ if (!pending) {
813
+ pending = agentApi
814
+ .joinKeys(tables)
815
+ .then((record) => (record.joins ?? []).filter((j) => typeof j?.predicate === "string"))
816
+ .catch((err) => {
817
+ console.error(`join_keys for ${set} failed; the statement runs unchecked: ${agentErr(err)}`);
818
+ keysAsked.delete(set);
819
+ return [];
820
+ });
821
+ keysAsked.set(set, pending);
822
+ }
823
+ return pending;
824
+ }
770
825
  server.registerTool("infino_sql", {
771
826
  title: "SQL over Infino",
772
827
  annotations: DESTRUCTIVE,
@@ -778,7 +833,17 @@ server.registerTool("infino_sql", {
778
833
  'where the vector goes and pass embed:{"name":"query text"} — the server embeds the text and substitutes the ' +
779
834
  "vector in. Example: SELECT path, SUM(end_line - start_line + 1) AS lines FROM " +
780
835
  "bm25_search('docs','body','error timeout', 300) GROUP BY path ORDER BY lines DESC. " +
781
- "Any single statement is allowed, DDL/DML included.",
836
+ "Any single statement is allowed, DDL/DML included." +
837
+ (agentApi
838
+ ? " On Infino Cloud a query that searches a text column has its rows checked against `question`: the " +
839
+ "result's `validation` says whether they answer it, and what the column holds nowhere if not. A GROUP BY " +
840
+ "over a search function with a k under 300 is refused, since its totals rank a share of the top k rather " +
841
+ "than the table."
842
+ : "") +
843
+ (agentTools
844
+ ? " A statement that joins tables must join them on a key infino_join_keys found; one that does not is " +
845
+ "refused with the keys."
846
+ : ""),
782
847
  inputSchema: {
783
848
  query: z
784
849
  .string()
@@ -789,11 +854,42 @@ server.registerTool("infino_sql", {
789
854
  .describe("Map of placeholder name -> query text. Each text is embedded with the server's embedder and its vector " +
790
855
  "is substituted for every {{name}} in the query — required to use vector_search / hybrid_search. " +
791
856
  'E.g. {"q":"error timeout"} fills {{q}}.'),
857
+ ...(agentApi
858
+ ? {
859
+ question: z
860
+ .string()
861
+ .optional()
862
+ .describe("The question these rows are meant to answer, in the words it was asked. Used only to check the " +
863
+ "rows against it; put nothing else here."),
864
+ }
865
+ : {}),
792
866
  },
793
- }, async ({ query, embed: embeds }) => {
867
+ }, async ({ query, embed: embeds, question }) => {
794
868
  try {
795
- const sql = await applyEmbeds(query, embeds);
796
- const { value: rows, tookMs } = timed(() => db.querySql(guardSql(sql)));
869
+ const sql = guardSql(await applyEmbeds(query, embeds));
870
+ const code = withoutComments(sql);
871
+ if (agentApi && agentTools) {
872
+ const verdict = await joinGate(code, knownTables(), keysAmong);
873
+ if (verdict.kind === "refuse")
874
+ return fail(joinRefusal("sql", verdict));
875
+ }
876
+ const searched = agentApi ? searchedTextColumn(code) : null;
877
+ if (agentApi && searched) {
878
+ const t0 = performance.now();
879
+ try {
880
+ const { rows, validation } = await agentApi.querySqlValidated(sql, {
881
+ ...searched,
882
+ ...(question ? { question } : {}),
883
+ });
884
+ return ok({ rows, validation, took_ms: Math.round((performance.now() - t0) * 1000) / 1000 });
885
+ }
886
+ catch (err) {
887
+ if (!validationUnavailable(err))
888
+ return fail(`sql failed: ${agentErr(err)}`);
889
+ // A deployment that cannot check results runs the query unchecked.
890
+ }
891
+ }
892
+ const { value: rows, tookMs } = timed(() => db.querySql(sql));
797
893
  return ok({ rows, took_ms: tookMs });
798
894
  }
799
895
  catch (err) {
@@ -877,24 +973,6 @@ server.registerTool("infino_delete_documents", {
877
973
  }
878
974
  });
879
975
  // --- 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
976
  if (agentApi && agentTools) {
899
977
  server.registerTool("infino_describe_columns", {
900
978
  title: "A table's column entries, by name or name family",
@@ -0,0 +1,290 @@
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
+ return aliases;
134
+ }
135
+ /** A statement or predicate reduced to what its join condition is made of:
136
+ * lowercase, aliases replaced by their tables, quotes and blanks gone. */
137
+ export function normalizeSql(text, aliases) {
138
+ let out = text.toLowerCase();
139
+ for (const [alias, table] of aliases) {
140
+ out = out.replace(new RegExp(`(?<![\\w.])${escapeRegex(alias)}\\.`, "g"), `${table.toLowerCase()}.`);
141
+ }
142
+ return out.replace(/["`]/g, "").replace(/\s+/g, "");
143
+ }
144
+ /** Whether `predicate` (`a.x = b.y`, either side possibly an expression) is
145
+ * written in the statement, either way round. */
146
+ export function predicateHolds(query, predicate, aliases) {
147
+ const statement = normalizeSql(query, aliases);
148
+ const sides = predicate.split(/\s=\s/);
149
+ if (sides.length !== 2)
150
+ return statement.includes(normalizeSql(predicate, aliases));
151
+ const [l, r] = sides.map((s) => normalizeSql(s, aliases));
152
+ return statement.includes(`${l}=${r}`) || statement.includes(`${r}=${l}`);
153
+ }
154
+ /** The set operators that put one query's rows after another's: the
155
+ * branches they separate join nothing to each other. */
156
+ const SET_OPERATOR = /\b(?:union(?:\s+all)?|intersect|except)\b/gi;
157
+ /** The opening of a subquery inside parentheses. */
158
+ const SUBQUERY_START = /^\s*(?:select|with)\b/i;
159
+ /** A FROM list that names several sources (`FROM a, b`): a join. */
160
+ const FROM_LIST = /\bfrom\b([\s\S]*?)(?:\bwhere\b|\bgroup\b|\border\b|\blimit\b|\bhaving\b|\bwindow\b|\bqualify\b|$)/gi;
161
+ /** The index just past the parenthesised group that opens at `open`, quotes
162
+ * skipped; the text's end when the group is never closed. */
163
+ function groupEnd(text, open) {
164
+ let depth = 0;
165
+ for (let i = open; i < text.length; i++) {
166
+ const c = text[i];
167
+ if (c === "'" || c === '"') {
168
+ const close = text.indexOf(c, i + 1);
169
+ i = close < 0 ? text.length : close;
170
+ }
171
+ else if (c === "(")
172
+ depth += 1;
173
+ else if (c === ")" && --depth === 0)
174
+ return i + 1;
175
+ }
176
+ return text.length;
177
+ }
178
+ /** A quoted text that can name a table: one identifier, as a search
179
+ * function's first argument does (`'chunks'`). Any other quoted text is a
180
+ * value, whatever words it holds. */
181
+ const QUOTED_NAME = /^['"][A-Za-z_]\w*['"]$/;
182
+ /** `text` with its subqueries taken out and blanked, and the subqueries
183
+ * themselves, at whatever depth they sit (inside a function call's
184
+ * arguments too). A parenthesised group that is not a query - a function's
185
+ * arguments, a search function's table - stays in place; a quoted value is
186
+ * blanked, a quoted name kept. */
187
+ function splitSubqueries(text) {
188
+ let outer = "";
189
+ const subqueries = [];
190
+ for (let i = 0; i < text.length;) {
191
+ const c = text[i];
192
+ if (c === "'" || c === '"') {
193
+ const close = text.indexOf(c, i + 1);
194
+ const end = close < 0 ? text.length : close + 1;
195
+ const quoted = text.slice(i, end);
196
+ outer += QUOTED_NAME.test(quoted) ? quoted : " ".repeat(quoted.length);
197
+ i = end;
198
+ }
199
+ else if (c === "(") {
200
+ const end = groupEnd(text, i);
201
+ const inner = text.slice(i + 1, Math.max(i + 1, end - 1));
202
+ if (SUBQUERY_START.test(inner)) {
203
+ subqueries.push(inner);
204
+ outer += " ".repeat(end - i);
205
+ }
206
+ else {
207
+ const nested = splitSubqueries(inner);
208
+ outer += `(${nested.outer})`;
209
+ subqueries.push(...nested.subqueries);
210
+ }
211
+ i = end;
212
+ }
213
+ else {
214
+ outer += c;
215
+ i += 1;
216
+ }
217
+ }
218
+ return { outer, subqueries };
219
+ }
220
+ /** `text` cut at its set operators outside parentheses and quotes. */
221
+ function setBranches(text) {
222
+ const { outer } = splitSubqueries(text);
223
+ const cuts = [];
224
+ for (const m of outer.matchAll(SET_OPERATOR))
225
+ cuts.push(m.index ?? 0, (m.index ?? 0) + m[0].length);
226
+ const branches = [];
227
+ let from = 0;
228
+ for (let k = 0; k < cuts.length; k += 2) {
229
+ branches.push(text.slice(from, cuts[k]));
230
+ from = cuts[k + 1];
231
+ }
232
+ branches.push(text.slice(from));
233
+ return branches;
234
+ }
235
+ /** Whether a statement joins known tables, so that its rows pair one
236
+ * table's with another's and the pairing must be on a key the data holds:
237
+ * two tables in one query's FROM or JOIN; a subquery over another table
238
+ * than the query around it (`IN (SELECT ... FROM b)`, a correlated
239
+ * subquery); or queries over different tables joined to each other (CTEs
240
+ * JOINed, or listed in one FROM). Queries that only sit side by side join
241
+ * nothing and run as written: the branches of a UNION, INTERSECT or EXCEPT
242
+ * (a count per table, say), and subqueries over one table each in a SELECT
243
+ * list with no table of its own. */
244
+ export function joinsTables(query, known) {
245
+ for (const branch of setBranches(query)) {
246
+ const { outer, subqueries } = splitSubqueries(branch);
247
+ const own = tablesNamed(outer, known);
248
+ if (own.length >= 2)
249
+ return true;
250
+ if (subqueries.some((sub) => joinsTables(sub, known)))
251
+ return true;
252
+ const below = [...new Set(subqueries.flatMap((sub) => tablesNamed(sub, known)))];
253
+ if (own.length === 1 && below.some((table) => table !== own[0]))
254
+ return true;
255
+ if (own.length === 0 && below.length >= 2) {
256
+ const joined = /\bjoin\b/i.test(outer) || [...outer.matchAll(FROM_LIST)].some((m) => m[1].includes(","));
257
+ if (joined)
258
+ return true;
259
+ }
260
+ }
261
+ return false;
262
+ }
263
+ /** The gate. `known` is every table the statement may name; `keys` fetches
264
+ * the service's joins among the named tables and is called only when the
265
+ * statement joins two or more of them (`joinsTables`). Pass the statement
266
+ * without its comments (`withoutComments`). */
267
+ export async function joinGate(query, known, keys) {
268
+ const unwalked = withoutGraphCalls(query);
269
+ const tables = tablesNamed(unwalked, known);
270
+ if (tables.length < 2)
271
+ return { kind: "run", tables, keysAsked: false };
272
+ if (!joinsTables(unwalked, known))
273
+ return { kind: "run", tables, keysAsked: false };
274
+ const joins = (await keys(tables)).filter((j) => tables.includes(j.from_table) && tables.includes(j.to_table));
275
+ // Two tables the service found no key between: nothing to hold the
276
+ // statement to; it runs as written.
277
+ if (joins.length === 0)
278
+ return { kind: "run", tables, keysAsked: true };
279
+ const aliases = aliasesOf(query, tables);
280
+ if (joins.some((j) => predicateHolds(query, j.predicate, aliases)))
281
+ return { kind: "run", tables, keysAsked: true };
282
+ return { kind: "refuse", tables, keys: joins };
283
+ }
284
+ /** The refusal's text: what was spanned, what joins it, what to do. */
285
+ export function joinRefusal(tool, verdict) {
286
+ const list = verdict.keys.map((j) => ` ${j.predicate}`).join("\n");
287
+ return (`${tool} refused: the statement spans ${verdict.tables.join(", ")} without a key Infino Cloud found on their ` +
288
+ `values. infino_join_keys says they join on:\n${list}\nRewrite the statement with one of these as its ON (or ` +
289
+ "WHERE) condition and run it again; a subquery or a condition on other columns is not a join the data supports.");
290
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infino-ai/mcp-server",
3
- "version": "0.18.0",
3
+ "version": "0.19.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,7 +58,7 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@huggingface/transformers": "^4.3.2",
61
- "@infino-ai/infino": "^0.11.17",
61
+ "@infino-ai/infino": "^0.11.24",
62
62
  "@modelcontextprotocol/sdk": "^1.32.2",
63
63
  "zod": "^4.6.5"
64
64
  },