@infino-ai/mcp-server 0.17.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 +19 -3
- package/dist/agent-api.js +208 -0
- package/dist/index.js +217 -8
- package/dist/join-gate.js +290 -0
- package/package.json +8 -8
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,22 @@ 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
|
+
|
|
304
|
+
### Agent tools (Infino Cloud)
|
|
305
|
+
|
|
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.
|
|
307
|
+
|
|
308
|
+
| Tool | Arguments | What it does |
|
|
309
|
+
| --- | --- | --- |
|
|
310
|
+
| `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. |
|
|
311
|
+
| `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`. |
|
|
312
|
+
| `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
|
+
|
|
298
314
|
### Writing data
|
|
299
315
|
|
|
300
316
|
The write path an agent follows, each step one tool call and one commit:
|
|
@@ -317,7 +333,7 @@ This server runs locally, beside the client, and keeps data and credentials on t
|
|
|
317
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.
|
|
318
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.
|
|
319
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.
|
|
320
|
-
- **Who can write is decided outside the server.**
|
|
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.
|
|
321
337
|
- **Least privilege.** Point `INFINO_MCP_URI` at the narrowest dataset the task needs, and supply storage credentials scoped to that bucket/prefix.
|
|
322
338
|
|
|
323
339
|
---
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// SPDX-FileCopyrightText: Copyright The Infino Authors
|
|
3
|
+
//
|
|
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
|
|
8
|
+
// HTTPS with the same API key the binding uses, and only on a hosted
|
|
9
|
+
// connection; an embedded catalog has none of these.
|
|
10
|
+
/** Split a hosted URI into its service base and database, or `null` when the
|
|
11
|
+
* URI names no database. */
|
|
12
|
+
export function hostedEndpoint(uri) {
|
|
13
|
+
let url;
|
|
14
|
+
try {
|
|
15
|
+
url = new URL(uri);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
const segments = url.pathname.split("/").filter((s) => s.length > 0);
|
|
21
|
+
const database = segments.pop();
|
|
22
|
+
if (!database)
|
|
23
|
+
return null;
|
|
24
|
+
const prefix = segments.length > 0 ? `/${segments.join("/")}` : "";
|
|
25
|
+
return { base: `${url.origin}${prefix}`, database: decodeURIComponent(database) };
|
|
26
|
+
}
|
|
27
|
+
/** A failed call to the service: the HTTP status, the service's own words,
|
|
28
|
+
* and when it said to try again, if it did. */
|
|
29
|
+
export class AgentApiError extends Error {
|
|
30
|
+
op;
|
|
31
|
+
status;
|
|
32
|
+
retryAfterSecs;
|
|
33
|
+
constructor(op, status, detail, retryAfterSecs) {
|
|
34
|
+
super(`${op}: the service answered ${status}: ${detail}` +
|
|
35
|
+
(retryAfterSecs !== undefined ? `; it is busy, so try again in ${retryAfterSecs} s` : ""));
|
|
36
|
+
this.op = op;
|
|
37
|
+
this.status = status;
|
|
38
|
+
this.retryAfterSecs = retryAfterSecs;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** How long an ask may take when the caller sets no budget of its own: the
|
|
42
|
+
* service runs a model loop, and stops it at its own cap before this. */
|
|
43
|
+
const ASK_TIMEOUT_MS = 600_000;
|
|
44
|
+
/** Wall clock an ask gets past its own budget: the loop may run right up to
|
|
45
|
+
* the budget, and the answer still has to travel back. */
|
|
46
|
+
const ASK_MARGIN_SECS = 60;
|
|
47
|
+
/** How long one call may take before it is given up on. A card or a join is a
|
|
48
|
+
* read of state the service keeps; the first join over a pair of tables counts
|
|
49
|
+
* it on the data, which is the slow case this allows for. */
|
|
50
|
+
const CALL_TIMEOUT_MS = 120_000;
|
|
51
|
+
/** How long the startup check waits: the server must come up even when the
|
|
52
|
+
* service is slow to answer, and a check that times out reads as off. */
|
|
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
|
+
}
|
|
75
|
+
/** The agent-route client for one hosted database. */
|
|
76
|
+
export class AgentApi {
|
|
77
|
+
endpoint;
|
|
78
|
+
apiKey;
|
|
79
|
+
fetchImpl;
|
|
80
|
+
constructor(endpoint, apiKey, fetchImpl = fetch) {
|
|
81
|
+
this.endpoint = endpoint;
|
|
82
|
+
this.apiKey = apiKey;
|
|
83
|
+
this.fetchImpl = fetchImpl;
|
|
84
|
+
}
|
|
85
|
+
/** Whether the account has the agent routes switched on. A service that
|
|
86
|
+
* does not know the features route (404) predates it and has none to
|
|
87
|
+
* offer; any other failure is reported to the caller, which decides. */
|
|
88
|
+
async agentApisEnabled() {
|
|
89
|
+
const response = await this.request("account features", `${this.endpoint.base}/v1/account/features`, {
|
|
90
|
+
method: "GET",
|
|
91
|
+
timeoutMs: FEATURES_TIMEOUT_MS,
|
|
92
|
+
notFoundIsAnswer: true,
|
|
93
|
+
});
|
|
94
|
+
if (response === null)
|
|
95
|
+
return false;
|
|
96
|
+
return response.agent_apis === true;
|
|
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
|
+
}
|
|
112
|
+
/** The column entries of `table`'s card whose names match `pattern`, most
|
|
113
|
+
* populated first, as the service's optimizer last described them. */
|
|
114
|
+
async describeColumns(table, lookup) {
|
|
115
|
+
const query = new URLSearchParams({ table, pattern: lookup.pattern });
|
|
116
|
+
if (lookup.limit !== undefined)
|
|
117
|
+
query.set("limit", String(lookup.limit));
|
|
118
|
+
return (await this.request("table_card", `${this.dataUrl("table_card")}?${query}`, {
|
|
119
|
+
method: "GET",
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
/** The keys two or more tables join on, found by the service on their
|
|
123
|
+
* values: each join's two sides, how much of one side's values the other
|
|
124
|
+
* holds, and the ON clause to paste. */
|
|
125
|
+
async joinKeys(tables) {
|
|
126
|
+
return (await this.request("join_keys", this.dataUrl("join_keys"), {
|
|
127
|
+
method: "POST",
|
|
128
|
+
body: JSON.stringify({ tables }),
|
|
129
|
+
}));
|
|
130
|
+
}
|
|
131
|
+
/** Ask the service's retrieval loop a question about the database: it
|
|
132
|
+
* chooses and runs the searches and SQL itself and returns the rows it
|
|
133
|
+
* found (`facts`), the statement whose rows answer the question
|
|
134
|
+
* (`statement`), and how many rows that returned (`coverage`); a loop that
|
|
135
|
+
* found no answer still returns, with `terminate` saying why. Only the
|
|
136
|
+
* fields given are sent, since the service refuses unknown ones. */
|
|
137
|
+
async ask(request) {
|
|
138
|
+
const body = { question: request.question };
|
|
139
|
+
if (request.context !== undefined)
|
|
140
|
+
body.context = request.context;
|
|
141
|
+
if (request.table !== undefined)
|
|
142
|
+
body.table = request.table;
|
|
143
|
+
if (request.tables !== undefined && request.tables.length > 0)
|
|
144
|
+
body.tables = request.tables;
|
|
145
|
+
if (request.k !== undefined)
|
|
146
|
+
body.k = request.k;
|
|
147
|
+
if (request.maxWallSecs !== undefined)
|
|
148
|
+
body.max_wall_secs = request.maxWallSecs;
|
|
149
|
+
const timeoutMs = request.maxWallSecs !== undefined ? (request.maxWallSecs + ASK_MARGIN_SECS) * 1000 : ASK_TIMEOUT_MS;
|
|
150
|
+
return (await this.request("ask", this.dataUrl("sub_agent"), {
|
|
151
|
+
method: "POST",
|
|
152
|
+
body: JSON.stringify(body),
|
|
153
|
+
timeoutMs,
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
dataUrl(op) {
|
|
157
|
+
return `${this.endpoint.base}/v1/${op}/${encodeURIComponent(this.endpoint.database)}`;
|
|
158
|
+
}
|
|
159
|
+
async request(op, url, options) {
|
|
160
|
+
const headers = {
|
|
161
|
+
authorization: `Bearer ${this.apiKey}`,
|
|
162
|
+
accept: "application/json",
|
|
163
|
+
};
|
|
164
|
+
if (options.body !== undefined)
|
|
165
|
+
headers["content-type"] = "application/json";
|
|
166
|
+
const response = await this.fetchImpl(url, {
|
|
167
|
+
method: options.method,
|
|
168
|
+
headers,
|
|
169
|
+
body: options.body,
|
|
170
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? CALL_TIMEOUT_MS),
|
|
171
|
+
});
|
|
172
|
+
if (response.status === 404 && options.notFoundIsAnswer)
|
|
173
|
+
return null;
|
|
174
|
+
const text = await response.text();
|
|
175
|
+
if (!response.ok) {
|
|
176
|
+
throw new AgentApiError(op, response.status, errorDetail(text), retryAfter(response));
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
return JSON.parse(text);
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
throw new AgentApiError(op, response.status, `not JSON: ${text.slice(0, 200)}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/** HTTP statuses the service answers when it is busy for now and the call
|
|
187
|
+
* may be made again: not ready yet (503), or at capacity (529). */
|
|
188
|
+
const BUSY_STATUSES = new Set([503, 529]);
|
|
189
|
+
/** The seconds a busy answer said to wait, from its `Retry-After` header. */
|
|
190
|
+
function retryAfter(response) {
|
|
191
|
+
if (!BUSY_STATUSES.has(response.status))
|
|
192
|
+
return undefined;
|
|
193
|
+
const secs = Number(response.headers.get("retry-after"));
|
|
194
|
+
return Number.isFinite(secs) && secs > 0 ? secs : undefined;
|
|
195
|
+
}
|
|
196
|
+
/** The service's error message from a failed response body: its `error`
|
|
197
|
+
* field when the body is the usual JSON envelope, else the text itself. */
|
|
198
|
+
function errorDetail(text) {
|
|
199
|
+
try {
|
|
200
|
+
const parsed = JSON.parse(text);
|
|
201
|
+
if (typeof parsed.error === "string")
|
|
202
|
+
return parsed.error;
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
// Not JSON: the text is the message.
|
|
206
|
+
}
|
|
207
|
+
return text.trim().slice(0, 500) || "(no body)";
|
|
208
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -14,12 +14,19 @@
|
|
|
14
14
|
// invented here; bulk ingestion, chunking, and upsert live in the CLI, the
|
|
15
15
|
// SDKs, or the engine.
|
|
16
16
|
//
|
|
17
|
-
//
|
|
17
|
+
// One deliberate exception: on Infino Cloud, an account can have the agent
|
|
18
|
+
// routes switched on, which describe a table, find the keys tables join on,
|
|
19
|
+
// and answer a question with the service's own retrieval loop. Those are not
|
|
20
|
+
// binding operations, so they are called over HTTPS (see agent-api.ts), and
|
|
21
|
+
// their tools are offered only on a hosted connection whose account has them
|
|
22
|
+
// on, checked once at startup. Everywhere else they do not appear.
|
|
23
|
+
//
|
|
24
|
+
// The binding's surface is always advertised. Who may write is decided by the
|
|
18
25
|
// hosted API key's capabilities (a read-scoped key gets 403 on writes) and by
|
|
19
26
|
// whoever configured the local path or bucket credentials; how much a client
|
|
20
27
|
// confirms before a destructive call is the client's decision, driven by the
|
|
21
28
|
// tool annotations below. There is no server-side write gate.
|
|
22
|
-
import { mkdirSync } from "node:fs";
|
|
29
|
+
import { mkdirSync, readFileSync } from "node:fs";
|
|
23
30
|
import { homedir } from "node:os";
|
|
24
31
|
import { join } from "node:path";
|
|
25
32
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -28,6 +35,8 @@ import { z } from "zod";
|
|
|
28
35
|
import { connect, IndexSpec } from "@infino-ai/infino";
|
|
29
36
|
import { embed, embedMany, embedderDim, embedderInfo } from "./embedding.js";
|
|
30
37
|
import { errText as translate, guardSql } from "./guards.js";
|
|
38
|
+
import { AgentApi, AgentApiError, hostedEndpoint, searchedTextColumn, validationUnavailable, } from "./agent-api.js";
|
|
39
|
+
import { joinGate, joinRefusal, withoutComments } from "./join-gate.js";
|
|
31
40
|
// --- connection (env-configured, opened once at startup) -------------------
|
|
32
41
|
//
|
|
33
42
|
// The agent never manages connections: the server is pointed at the data via
|
|
@@ -306,7 +315,10 @@ async function embedRows(handle, rows, table) {
|
|
|
306
315
|
// Server-level instructions are returned to the client on initialize and shown
|
|
307
316
|
// to the model — the highest-leverage place to position Infino and steer which
|
|
308
317
|
// tool fires when. Kept factual and answer-first (no keyword stuffing).
|
|
309
|
-
|
|
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 }, {
|
|
310
322
|
instructions: "Infino is an embedded retrieval engine for data on object storage: full-text (BM25), vector, " +
|
|
311
323
|
"hybrid, and SQL search over one copy of the data, in-process, with no separate server or managed " +
|
|
312
324
|
"service. Tables are stored as valid Parquet; DuckDB or pyarrow can read the same files. These tools " +
|
|
@@ -759,6 +771,57 @@ server.registerTool("infino_count", {
|
|
|
759
771
|
return fail(`count failed: ${errText(err)}`);
|
|
760
772
|
}
|
|
761
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
|
+
}
|
|
762
825
|
server.registerTool("infino_sql", {
|
|
763
826
|
title: "SQL over Infino",
|
|
764
827
|
annotations: DESTRUCTIVE,
|
|
@@ -770,7 +833,17 @@ server.registerTool("infino_sql", {
|
|
|
770
833
|
'where the vector goes and pass embed:{"name":"query text"} — the server embeds the text and substitutes the ' +
|
|
771
834
|
"vector in. Example: SELECT path, SUM(end_line - start_line + 1) AS lines FROM " +
|
|
772
835
|
"bm25_search('docs','body','error timeout', 300) GROUP BY path ORDER BY lines DESC. " +
|
|
773
|
-
"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
|
+
: ""),
|
|
774
847
|
inputSchema: {
|
|
775
848
|
query: z
|
|
776
849
|
.string()
|
|
@@ -781,11 +854,42 @@ server.registerTool("infino_sql", {
|
|
|
781
854
|
.describe("Map of placeholder name -> query text. Each text is embedded with the server's embedder and its vector " +
|
|
782
855
|
"is substituted for every {{name}} in the query — required to use vector_search / hybrid_search. " +
|
|
783
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
|
+
: {}),
|
|
784
866
|
},
|
|
785
|
-
}, async ({ query, embed: embeds }) => {
|
|
867
|
+
}, async ({ query, embed: embeds, question }) => {
|
|
786
868
|
try {
|
|
787
|
-
const sql = await applyEmbeds(query, embeds);
|
|
788
|
-
const
|
|
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));
|
|
789
893
|
return ok({ rows, took_ms: tookMs });
|
|
790
894
|
}
|
|
791
895
|
catch (err) {
|
|
@@ -868,10 +972,115 @@ server.registerTool("infino_delete_documents", {
|
|
|
868
972
|
return fail(`delete_documents failed: ${errText(err, "write")}`);
|
|
869
973
|
}
|
|
870
974
|
});
|
|
975
|
+
// --- agent tools (Infino Cloud accounts with the agent routes on) ----------
|
|
976
|
+
if (agentApi && agentTools) {
|
|
977
|
+
server.registerTool("infino_describe_columns", {
|
|
978
|
+
title: "A table's column entries, by name or name family",
|
|
979
|
+
annotations: READ_ONLY,
|
|
980
|
+
description: "List a table's column entries from its card, as Infino Cloud last computed them from the table itself: " +
|
|
981
|
+
"type, index role, rows with a value, distinct count, range and most frequent values. A wide table has " +
|
|
982
|
+
"more columns than infino_describe_table usefully shows; call this with a column's name, or a family " +
|
|
983
|
+
"prefix such as `property_*`, before a statement names one of them. Returns how many columns matched " +
|
|
984
|
+
"and the first 40 by rows with a value, or `limit` of them.",
|
|
985
|
+
inputSchema: {
|
|
986
|
+
table: z.string().min(1).describe("The table to describe."),
|
|
987
|
+
pattern: z
|
|
988
|
+
.string()
|
|
989
|
+
.min(1)
|
|
990
|
+
.describe("A column name, matched whole; `*` matches any run of characters, for a prefix (`property_*`) " +
|
|
991
|
+
"or a word anywhere in the name (`*monthly*`); or `*` for every column. Case does not matter."),
|
|
992
|
+
limit: z
|
|
993
|
+
.number()
|
|
994
|
+
.int()
|
|
995
|
+
.positive()
|
|
996
|
+
.optional()
|
|
997
|
+
.describe("Entries to list, most rows with a value first (default 40)."),
|
|
998
|
+
},
|
|
999
|
+
}, async ({ table, pattern, limit }) => {
|
|
1000
|
+
try {
|
|
1001
|
+
const record = await agentApi.describeColumns(table, { pattern, limit });
|
|
1002
|
+
const card = (record.card ?? record);
|
|
1003
|
+
const columns = Array.isArray(card.schema) ? card.schema : [];
|
|
1004
|
+
const matched = typeof record.matched === "number" ? record.matched : columns.length;
|
|
1005
|
+
return ok({ table, pattern, matched, listed: columns.length, columns });
|
|
1006
|
+
}
|
|
1007
|
+
catch (err) {
|
|
1008
|
+
return fail(`describe_columns failed: ${agentErr(err)}`);
|
|
1009
|
+
}
|
|
1010
|
+
});
|
|
1011
|
+
server.registerTool("infino_join_keys", {
|
|
1012
|
+
title: "The keys two or more tables join on, found on their values",
|
|
1013
|
+
annotations: READ_ONLY,
|
|
1014
|
+
description: "The keys the named tables join on, found by Infino Cloud on the tables' values, never by matching " +
|
|
1015
|
+
"column names: which columns hold each other's values, and through which expression where they meet " +
|
|
1016
|
+
"only through one. Each join comes back with its two sides, the share of the referencing side's values " +
|
|
1017
|
+
"found on the other, and `predicate`, the ON clause ready to paste into infino_sql. Call it before " +
|
|
1018
|
+
"writing a statement across tables.",
|
|
1019
|
+
inputSchema: {
|
|
1020
|
+
tables: z.array(z.string().min(1)).min(2).max(8).describe("The tables the statement will span."),
|
|
1021
|
+
},
|
|
1022
|
+
}, async ({ tables }) => {
|
|
1023
|
+
try {
|
|
1024
|
+
return ok(await agentApi.joinKeys(tables));
|
|
1025
|
+
}
|
|
1026
|
+
catch (err) {
|
|
1027
|
+
return fail(`join_keys failed: ${agentErr(err)}`);
|
|
1028
|
+
}
|
|
1029
|
+
});
|
|
1030
|
+
server.registerTool("infino_ask", {
|
|
1031
|
+
title: "Ask a question of the data: one retrieval, the rows back",
|
|
1032
|
+
annotations: READ_ONLY,
|
|
1033
|
+
description: "Ask a question about this database in plain language. A retrieval agent on Infino Cloud reads the " +
|
|
1034
|
+
"tables' cards, chooses and runs the searches and SQL itself (joins included), checks the result " +
|
|
1035
|
+
"against the question, and returns the rows it found (`facts`), the statement whose rows answer the " +
|
|
1036
|
+
"question (`statement`), and how many rows that statement returned (`coverage`). It never writes a " +
|
|
1037
|
+
"summary: read the rows, and reuse `statement` with infino_sql to go further. Use it for any question " +
|
|
1038
|
+
"that is not one statement you already know how to write: where a value lives, which column holds a " +
|
|
1039
|
+
"name, counts and rankings across tables. Several asks in one reply run at the same time. When the " +
|
|
1040
|
+
"database holds several tables and the question is about one or a few, name them in `table` or " +
|
|
1041
|
+
"`tables`. Each ask runs a model loop on the service: it takes seconds to a few minutes and its model " +
|
|
1042
|
+
"calls are billed to the account, so when you already know the statement, run it with infino_sql " +
|
|
1043
|
+
"instead. A loop that found no answer still returns, with `terminate` saying why; if an ask comes back " +
|
|
1044
|
+
"thin, rephrase it, narrower or broader, and ask again.",
|
|
1045
|
+
inputSchema: {
|
|
1046
|
+
question: z
|
|
1047
|
+
.string()
|
|
1048
|
+
.min(1)
|
|
1049
|
+
.describe("The question, about the data, in plain language. Its names, numbers and quoted terms are what " +
|
|
1050
|
+
"the result is checked for, so put only the question here."),
|
|
1051
|
+
table: z.string().min(1).optional().describe("The one table the question is about."),
|
|
1052
|
+
tables: z
|
|
1053
|
+
.array(z.string().min(1))
|
|
1054
|
+
.min(1)
|
|
1055
|
+
.max(8)
|
|
1056
|
+
.optional()
|
|
1057
|
+
.describe("The few tables the question is about, which the agent may join."),
|
|
1058
|
+
k: z.number().int().min(1).max(1000).optional().describe("Rows to return at most (default 10)."),
|
|
1059
|
+
context: z
|
|
1060
|
+
.string()
|
|
1061
|
+
.optional()
|
|
1062
|
+
.describe("Anything the agent should know beside the question (a convention, a definition); not checked for."),
|
|
1063
|
+
maxWallSecs: z
|
|
1064
|
+
.number()
|
|
1065
|
+
.int()
|
|
1066
|
+
.min(10)
|
|
1067
|
+
.max(600)
|
|
1068
|
+
.optional()
|
|
1069
|
+
.describe("A shorter time budget in seconds than the service's own, for a cheaper, faster ask."),
|
|
1070
|
+
},
|
|
1071
|
+
}, async (request) => {
|
|
1072
|
+
try {
|
|
1073
|
+
return ok(await agentApi.ask(request));
|
|
1074
|
+
}
|
|
1075
|
+
catch (err) {
|
|
1076
|
+
return fail(`ask failed: ${agentErr(err)}`);
|
|
1077
|
+
}
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
871
1080
|
// --- transport -------------------------------------------------------------
|
|
872
1081
|
// stdio for desktop/CLI clients (Claude Desktop/Code, Cursor). Logs go to
|
|
873
1082
|
// stderr so they never corrupt the JSON-RPC stream on stdout.
|
|
874
1083
|
const transport = new StdioServerTransport();
|
|
875
1084
|
await server.connect(transport);
|
|
876
1085
|
console.error(`infino MCP server ready on stdio (uri: ${uri}, mode: ${isHosted ? "hosted" : "embedded"}, ` +
|
|
877
|
-
`embedder: ${embedderInfo()})`);
|
|
1086
|
+
`embedder: ${embedderInfo()}, agent tools: ${agentTools ? "on" : "off"})`);
|
|
@@ -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.
|
|
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",
|
|
@@ -57,18 +57,18 @@
|
|
|
57
57
|
"audit:gate": "node scripts/audit-gate.mjs"
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@huggingface/transformers": "^4.2
|
|
61
|
-
"@infino-ai/infino": "^0.11.
|
|
62
|
-
"@modelcontextprotocol/sdk": "^1.32.
|
|
60
|
+
"@huggingface/transformers": "^4.3.2",
|
|
61
|
+
"@infino-ai/infino": "^0.11.24",
|
|
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.
|
|
69
|
-
"globals": "^17.
|
|
70
|
-
"prettier": "^3.9.
|
|
68
|
+
"eslint": "^10.14.0",
|
|
69
|
+
"globals": "^17.14.0",
|
|
70
|
+
"prettier": "^3.9.10",
|
|
71
71
|
"typescript": "^6.0.3",
|
|
72
|
-
"typescript-eslint": "^8.
|
|
72
|
+
"typescript-eslint": "^8.72.1"
|
|
73
73
|
}
|
|
74
74
|
}
|