@casoon/opengrid-mcp 0.0.0-stage → 0.13.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/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@casoon/opengrid-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.13.0",
4
+ "description": "opengrid as an MCP App: the grid in a chat client, driven by keyboard and by the model through one view",
5
+ "type": "module",
6
+ "license": "MIT OR Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/casoon/opengrid.git",
10
+ "directory": "packages/opengrid-mcp"
11
+ },
12
+ "bin": {
13
+ "opengrid-mcp": "src/server.mjs"
14
+ },
15
+ "files": [
16
+ "src",
17
+ "dist/view.html",
18
+ "README.md",
19
+ "LICENSE-MIT",
20
+ "LICENSE-APACHE"
21
+ ],
22
+ "dependencies": {
23
+ "@modelcontextprotocol/client": "^2.2.0",
24
+ "@modelcontextprotocol/ext-apps": "^2.0.3",
25
+ "@modelcontextprotocol/server": "^2.2.0",
26
+ "zod": "^4.6.5",
27
+ "@casoon/opengrid": "0.13.0"
28
+ },
29
+ "devDependencies": {
30
+ "esbuild": "0.28.2"
31
+ },
32
+ "engines": {
33
+ "node": ">=22.12.0"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "scripts": {
39
+ "build": "node scripts/build-view.mjs",
40
+ "test": "node --test test/*.test.mjs"
41
+ }
6
42
  }
package/src/config.mjs ADDED
@@ -0,0 +1,81 @@
1
+ // The operator's configuration (#140): which sources exist. The model names a
2
+ // source; it never names a path, writes SQL or reaches a network.
3
+ //
4
+ // opengrid-mcp.json:
5
+ // { "sources": { "orders": { "csv": "data/orders.csv", "schema": "data/orders.schema.json",
6
+ // "columns": ["id", "customer", "country", "amount"],
7
+ // "fields": ["id", "customer", "country", "amount", "qty"] } } }
8
+ //
9
+ // Paths are relative to the configuration file. `columns` are the grid's
10
+ // columns (its `columns` attribute); `fields` is the allow-list of fields a
11
+ // query may name — absent, every field of the schema.
12
+ //
13
+ // A source may also be one of an opengrid-server (#150):
14
+ // "remote": { "server": { "url": "https://…", "source": "orders", "tokenEnv": "ORDERS_TOKEN" } }
15
+ import { readFileSync } from "node:fs";
16
+ import { dirname, resolve } from "node:path";
17
+ import { z } from "zod";
18
+
19
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
20
+
21
+ const File = z
22
+ .object({
23
+ csv: z.string().min(1),
24
+ schema: z.string().min(1),
25
+ columns: z.array(z.string().regex(NAME)).min(1).optional(),
26
+ fields: z.array(z.string().regex(NAME)).min(1).optional(),
27
+ title: z.string().optional(),
28
+ })
29
+ .strict();
30
+
31
+ // A source of an opengrid-server (#150): its rules are the server's, so there
32
+ // is no `fields` here — the server narrows.
33
+ const OnServer = z
34
+ .object({
35
+ server: z
36
+ .object({
37
+ url: z.string().url(),
38
+ source: z.string().regex(NAME).optional(),
39
+ tokenEnv: z.string().min(1).optional(),
40
+ token: z.string().min(1).optional(),
41
+ })
42
+ .strict()
43
+ .refine((server) => !(server.token && server.tokenEnv), { message: "token or tokenEnv, not both" }),
44
+ columns: z.array(z.string().regex(NAME)).min(1).optional(),
45
+ title: z.string().optional(),
46
+ })
47
+ .strict();
48
+
49
+ const Source = z.union([File, OnServer]);
50
+
51
+ const Config = z
52
+ .object({
53
+ sources: z.record(z.string().regex(NAME), Source).refine((sources) => Object.keys(sources).length > 0, {
54
+ message: "at least one source",
55
+ }),
56
+ })
57
+ .strict();
58
+
59
+ /** Reads and checks the configuration; paths come back absolute. */
60
+ export function loadConfig(path) {
61
+ const file = resolve(path);
62
+ let raw;
63
+ try {
64
+ raw = JSON.parse(readFileSync(file, "utf8"));
65
+ } catch (error) {
66
+ throw new Error(`opengrid-mcp: cannot read ${file}: ${error.message}`);
67
+ }
68
+ const parsed = Config.safeParse(raw);
69
+ if (!parsed.success) {
70
+ const problems = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`);
71
+ throw new Error(`opengrid-mcp: ${file} is not a valid configuration:\n ${problems.join("\n ")}`);
72
+ }
73
+ const base = dirname(file);
74
+ const sources = {};
75
+ for (const [name, source] of Object.entries(parsed.data.sources)) {
76
+ sources[name] = source.server
77
+ ? source
78
+ : { ...source, csv: resolve(base, source.csv), schema: resolve(base, source.schema) };
79
+ }
80
+ return { sources };
81
+ }
package/src/data.mjs ADDED
@@ -0,0 +1,212 @@
1
+ // The sources — a CSV in opengrid's engine (WebAssembly in Node), or a source
2
+ // of an opengrid-server (#150). The rows stay here or there; the view and the
3
+ // model see answers to queries (#140).
4
+ //
5
+ // The allow-list works as the server's does (`opengrid-server`, narrowing the
6
+ // schema): a query is first checked against an empty copy of the source that
7
+ // has only the allowed fields, then run on the rows.
8
+ import { readFileSync } from "node:fs";
9
+ import { createRequire } from "node:module";
10
+ import { initSync, Engine } from "@casoon/opengrid/engine/opengrid_wasm.js";
11
+
12
+ const require = createRequire(import.meta.url);
13
+ initSync({ module: readFileSync(require.resolve("@casoon/opengrid/engine/opengrid_wasm_bg.wasm")) });
14
+
15
+ /** An error with a code, for the tools' answers. */
16
+ export class DataError extends Error {
17
+ constructor(code, message, path) {
18
+ super(message);
19
+ this.code = code;
20
+ this.path = path;
21
+ }
22
+ }
23
+
24
+ function csvField(name) {
25
+ return /[",\n]/.test(name) ? `"${name.replaceAll('"', '""')}"` : name;
26
+ }
27
+
28
+ /** The fields of a schema a CSV holds: a derived field (`from`) is computed. */
29
+ function headerOf(fields) {
30
+ return `${fields.filter((field) => !field.from).map((field) => csvField(field.name)).join(",")}\n`;
31
+ }
32
+
33
+ /** An `opengrid-server`'s error answer as a DataError, or its status in words. */
34
+ function refusal(status, text) {
35
+ try {
36
+ const { error } = JSON.parse(text);
37
+ return new DataError(error.code, error.message, error.path);
38
+ } catch {
39
+ return new DataError("backend", `the server answered ${status}`);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * A source of an `opengrid-server` (issue #150): its token, its allow-list and
45
+ * its row filter are the server's; here it is described once and asked by
46
+ * query.
47
+ */
48
+ async function serverSource(name, server, token) {
49
+ const base = server.url.replace(/\/$/, "");
50
+ const remote = server.source ?? name;
51
+ const headers = token ? { Authorization: `Bearer ${token}` } : {};
52
+ let response;
53
+ try {
54
+ response = await fetch(`${base}/source/${encodeURIComponent(remote)}`, { headers, redirect: "error" });
55
+ } catch (error) {
56
+ const unreachable = new Error(
57
+ `opengrid-mcp: source ${name}: ${base} cannot be reached: ${error.cause?.message ?? error.message}`,
58
+ );
59
+ unreachable.unreachable = true;
60
+ throw unreachable;
61
+ }
62
+ const text = await response.text();
63
+ if (!response.ok) {
64
+ throw new Error(`opengrid-mcp: source ${name}: ${base} refused: ${refusal(response.status, text).message}`);
65
+ }
66
+ const { schema } = JSON.parse(text);
67
+ const run = async (query) => {
68
+ const answer = await fetch(`${base}/query/${encodeURIComponent(remote)}`, {
69
+ method: "POST",
70
+ headers: { ...headers, "Content-Type": "application/json", Accept: "application/json" },
71
+ body: JSON.stringify({ ...query, source: remote }),
72
+ redirect: "error",
73
+ });
74
+ const body = await answer.text();
75
+ if (!answer.ok) throw refusal(answer.status, body);
76
+ return body;
77
+ };
78
+ return { schema, run };
79
+ }
80
+
81
+ export class Data {
82
+ /**
83
+ * Reads the sources. A server source is described once, here — or, when its
84
+ * server cannot be reached now, when it is next asked for (`ready`).
85
+ */
86
+ static async load(config) {
87
+ const data = new Data();
88
+ for (const [name, source] of Object.entries(config.sources)) {
89
+ if (source.server) {
90
+ const { tokenEnv } = source.server;
91
+ if (tokenEnv && !process.env[tokenEnv]) {
92
+ throw new Error(`opengrid-mcp: source ${name}: the environment variable ${tokenEnv} is not set`);
93
+ }
94
+ data.waiting.set(name, source);
95
+ } else {
96
+ const schema = JSON.parse(readFileSync(source.schema, "utf8"));
97
+ const allowed = source.fields ?? schema.fields.map((field) => field.name);
98
+ const unknown = allowed.filter((field) => !schema.fields.some((f) => f.name === field));
99
+ if (unknown.length) {
100
+ throw new Error(`opengrid-mcp: source ${name}: fields not in the schema: ${unknown.join(", ")}`);
101
+ }
102
+ data.engine.load_csv(name, readFileSync(source.csv), JSON.stringify(schema));
103
+ data.add(name, source, schema, allowed, async (query) => data.engine.execute(JSON.stringify(query)));
104
+ }
105
+ }
106
+ // A server that is down keeps the others from nothing: its source says so
107
+ // when asked. One that refuses is configured wrong and stops the start.
108
+ for (const name of data.waiting.keys()) {
109
+ await data.ready(name).catch((error) => {
110
+ if (error.code !== "unavailable") throw error;
111
+ console.error(error.message);
112
+ });
113
+ }
114
+ return data;
115
+ }
116
+
117
+ constructor() {
118
+ this.engine = new Engine();
119
+ this.checker = new Engine();
120
+ this.sources = new Map();
121
+ // Server sources not described yet, and those being described now.
122
+ this.waiting = new Map();
123
+ this.describing = new Map();
124
+ }
125
+
126
+ /** Describes a waiting server source; a no-op for any other name. */
127
+ async ready(name) {
128
+ const source = this.waiting.get(name);
129
+ if (!source) return;
130
+ if (!this.describing.has(name)) {
131
+ const { server } = source;
132
+ const token = server.tokenEnv ? process.env[server.tokenEnv] : server.token;
133
+ const describing = serverSource(name, server, token)
134
+ .then(({ schema, run }) => {
135
+ this.add(name, source, schema, schema.fields.map((field) => field.name), run);
136
+ this.waiting.delete(name);
137
+ })
138
+ .finally(() => this.describing.delete(name));
139
+ this.describing.set(name, describing);
140
+ }
141
+ try {
142
+ await this.describing.get(name);
143
+ } catch (error) {
144
+ throw new DataError(error.unreachable ? "unavailable" : "backend", error.message, "source");
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Registers a source: its narrowed schema in the checker (an empty copy a
150
+ * query is checked against first, as `opengrid-server` narrows its schema),
151
+ * and how it runs a query.
152
+ */
153
+ add(name, source, schema, allowed, run) {
154
+ // A derived field stays only when the field it is derived from is allowed.
155
+ const narrowed = {
156
+ ...schema,
157
+ fields: schema.fields.filter(
158
+ (field) => allowed.includes(field.name) && (!field.from || allowed.includes(field.from.field)),
159
+ ),
160
+ };
161
+ this.checker.load_csv(name, new TextEncoder().encode(headerOf(narrowed.fields)), JSON.stringify(narrowed));
162
+ const names = narrowed.fields.map((field) => field.name);
163
+ const columns = (source.columns ?? names).filter((column) => names.includes(column));
164
+ this.sources.set(name, { title: source.title ?? name, fields: narrowed.fields, columns, run });
165
+ }
166
+
167
+ /** The names of the sources. */
168
+ names() {
169
+ return [...this.sources.keys(), ...this.waiting.keys()];
170
+ }
171
+
172
+ source(name) {
173
+ const source = this.sources.get(name);
174
+ if (!source) {
175
+ throw new DataError("unknown_source", `no source ${JSON.stringify(name)}; there are: ${this.names().join(", ")}`, "source");
176
+ }
177
+ return source;
178
+ }
179
+
180
+ /**
181
+ * Runs a query (an object) on the source it names, after checking it
182
+ * against the allowed fields. Answers the result in the wire JSON.
183
+ */
184
+ async execute(query) {
185
+ const source = this.source(query.source);
186
+ try {
187
+ this.checker.execute(JSON.stringify(query));
188
+ } catch (error) {
189
+ throw new DataError("validation", String(error.message ?? error), "query");
190
+ }
191
+ return source.run(query);
192
+ }
193
+
194
+ /** How many rows a query matches. */
195
+ async count(query) {
196
+ const { limit, offset, ...whole } = query;
197
+ return JSON.parse(await this.execute({ ...whole, limit: 0 })).total_count;
198
+ }
199
+
200
+ /**
201
+ * The query of a view on the source's grid (issue #144), checked against the
202
+ * allowed fields: a view naming any other column is refused as a whole.
203
+ */
204
+ viewQuery(name, view) {
205
+ const source = this.source(name);
206
+ try {
207
+ return JSON.parse(this.checker.view_query(name, JSON.stringify(source.columns), JSON.stringify(view ?? {})));
208
+ } catch (error) {
209
+ throw new DataError("validation", String(error.message ?? error), "view");
210
+ }
211
+ }
212
+ }
package/src/rows.mjs ADDED
@@ -0,0 +1,30 @@
1
+ // Rows as objects, `{ column: value }` in the wire notation — the shape
2
+ // `@casoon/chartlet-mcp` reads (#140, point 11).
3
+
4
+ /** The rows of a result in the wire JSON, as objects. */
5
+ export function rowsOf(resultJson) {
6
+ const result = typeof resultJson === "string" ? JSON.parse(resultJson) : resultJson;
7
+ const rows = [];
8
+ for (let index = 0; index < result.row_count; index += 1) {
9
+ const row = {};
10
+ for (const column of result.columns) {
11
+ row[column.name] = column.values[index];
12
+ }
13
+ rows.push(row);
14
+ }
15
+ return rows;
16
+ }
17
+
18
+ /** Ascending positions as `[offset, limit]` runs — one query per run. */
19
+ export function runsOf(positions) {
20
+ const runs = [];
21
+ for (const position of positions) {
22
+ const last = runs.at(-1);
23
+ if (last && last[0] + last[1] === position) {
24
+ last[1] += 1;
25
+ } else {
26
+ runs.push([position, 1]);
27
+ }
28
+ }
29
+ return runs;
30
+ }
package/src/server.mjs ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ // @casoon/opengrid-mcp over stdio (#140): Claude Desktop starts it with
3
+ // npx -y @casoon/opengrid-mcp --config /path/to/opengrid-mcp.json
4
+ import { readFileSync, realpathSync } from "node:fs";
5
+ import { fileURLToPath } from "node:url";
6
+ import { McpServer } from "@modelcontextprotocol/server";
7
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
8
+
9
+ import { loadConfig } from "./config.mjs";
10
+ import { Data } from "./data.mjs";
11
+ import { Sessions } from "./sessions.mjs";
12
+ import { registerTools } from "./tools.mjs";
13
+
14
+ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
15
+
16
+ /** A server over the configured sources — the factory the transports use. */
17
+ export async function createServer(config) {
18
+ const data = await Data.load(config);
19
+ const sessions = new Sessions();
20
+ return () => {
21
+ const server = new McpServer({ name: "opengrid", version: VERSION }, { capabilities: { tools: {}, resources: {} } });
22
+ registerTools(server, data, sessions);
23
+ return server;
24
+ };
25
+ }
26
+
27
+ function configPath(args) {
28
+ const at = args.indexOf("--config");
29
+ if (at >= 0 && args[at + 1]) return args[at + 1];
30
+ return process.env.OPENGRID_MCP_CONFIG ?? "opengrid-mcp.json";
31
+ }
32
+
33
+ // Run as the bin (also through npx's symlink), not when imported by a test.
34
+ const main = process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
35
+ if (main) {
36
+ const factory = await createServer(loadConfig(configPath(process.argv.slice(2))));
37
+ serveStdio(factory);
38
+ }
@@ -0,0 +1,59 @@
1
+ // One session per grid the model opened (#140). The server keeps each
2
+ // session's view as the truth: the model writes it with opengrid_set_view, the
3
+ // reader's changes arrive through opengrid_sync, and a rendered view picks up
4
+ // the model's when it next syncs (E40).
5
+ import { randomUUID } from "node:crypto";
6
+
7
+ export class Sessions {
8
+ constructor() {
9
+ this.sessions = new Map();
10
+ }
11
+
12
+ open(source, view, query, total) {
13
+ const session = {
14
+ id: randomUUID(),
15
+ source,
16
+ view,
17
+ query,
18
+ total,
19
+ // Positions under `query`, as `opengrid-selection-change` names them.
20
+ selected: [],
21
+ // Bumped by every change; `origin` says whose it was.
22
+ revision: 1,
23
+ origin: "model",
24
+ // The revision of the model's last view: a reader's change made on an
25
+ // older one was made on a view the reader no longer has.
26
+ modelRevision: 1,
27
+ };
28
+ this.sessions.set(session.id, session);
29
+ return session;
30
+ }
31
+
32
+ get(id) {
33
+ return this.sessions.get(id);
34
+ }
35
+
36
+ /** The model's view: the selection goes with the old one, as in the grid. */
37
+ setView(session, view, query, total) {
38
+ Object.assign(session, { view, query, total, selected: [], origin: "model" });
39
+ session.revision += 1;
40
+ session.modelRevision = session.revision;
41
+ }
42
+
43
+ /** Whether a change made at `revision` was made before the model's last view. */
44
+ isStale(session, revision) {
45
+ return revision < session.modelRevision;
46
+ }
47
+
48
+ /** What the reader did, as the rendered grid reports it. */
49
+ readerChanged(session, change) {
50
+ Object.assign(session, {
51
+ view: change.view ?? session.view,
52
+ query: change.query ?? session.query,
53
+ total: change.total ?? session.total,
54
+ selected: change.selected ?? session.selected,
55
+ origin: "reader",
56
+ });
57
+ session.revision += 1;
58
+ }
59
+ }