@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/src/tools.mjs ADDED
@@ -0,0 +1,268 @@
1
+ // The tools of @casoon/opengrid-mcp (#140). opengrid knows nothing of MCP:
2
+ // everything here is the public API — a view, the query of a view, a query.
3
+ import { readFileSync, existsSync } from "node:fs";
4
+ import { fileURLToPath } from "node:url";
5
+ import { registerAppResource, registerAppTool, RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps/server";
6
+ import { z } from "zod";
7
+
8
+ import { DataError } from "./data.mjs";
9
+ import { rowsOf, runsOf } from "./rows.mjs";
10
+
11
+ export const GRID_URI = "ui://opengrid/grid";
12
+ const VIEW_HTML = fileURLToPath(new URL("../dist/view.html", import.meta.url));
13
+
14
+ /** The selection's default and largest answer (point 11). */
15
+ export const SELECTION_LIMIT = 100;
16
+ export const SELECTION_MAX = 500;
17
+
18
+ const View = z.record(z.string(), z.unknown()).describe(
19
+ "A grid view, exactly the JSON of opengrid's get_view: sort, filters, columns, density, group, expanded, aggregates, filter_row, facets. Fields left out keep their defaults.",
20
+ );
21
+
22
+ function answer(structured, text) {
23
+ return { structuredContent: structured, content: [{ type: "text", text: text ?? JSON.stringify(structured) }] };
24
+ }
25
+
26
+ function failure(error) {
27
+ const body =
28
+ error instanceof DataError
29
+ ? { code: error.code, message: error.message, path: error.path }
30
+ : { code: "internal", message: String(error.message ?? error) };
31
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: body }) }] };
32
+ }
33
+
34
+ function guarded(handler) {
35
+ return async (args) => {
36
+ try {
37
+ return await handler(args);
38
+ } catch (error) {
39
+ return failure(error);
40
+ }
41
+ };
42
+ }
43
+
44
+ function sessionOf(sessions, id) {
45
+ const session = sessions.get(id);
46
+ if (!session) {
47
+ throw new DataError("unknown_session", `no session ${JSON.stringify(id)}; open one with opengrid_open`, "sessionId");
48
+ }
49
+ return session;
50
+ }
51
+
52
+ /** The columns a session shows, with their types. */
53
+ function columnsOf(data, source) {
54
+ const { fields, columns } = data.source(source);
55
+ return columns.map((name) => {
56
+ const field = fields.find((f) => f.name === name);
57
+ return { name, type: field.type, nullable: field.nullable ?? true };
58
+ });
59
+ }
60
+
61
+ /** One line for the model: what the grid shows. */
62
+ function summary(session) {
63
+ const view = session.view ?? {};
64
+ const parts = [];
65
+ const filters = (view.filters ?? []).map((entry) => `${entry.column} ${entry.op} ${entry.value ?? ""}`.trim());
66
+ if (filters.length) parts.push(`Filter: ${filters.join(", ")}`);
67
+ const sort = (view.sort ?? []).map((key) => `${key.field} ${key.direction ?? "asc"}`);
68
+ if (sort.length) parts.push(`Sort: ${sort.join(", ")}`);
69
+ if (view.group?.length) parts.push(`Grouped by: ${view.group.join(", ")}`);
70
+ parts.push(`${session.total} matches`);
71
+ if (session.selected.length) parts.push(`${session.selected.length} selected`);
72
+ return parts.join(" · ");
73
+ }
74
+
75
+ export function registerTools(server, data, sessions) {
76
+ registerAppResource(
77
+ server,
78
+ "opengrid grid",
79
+ GRID_URI,
80
+ { description: "An accessible data grid over a source of the opengrid MCP server" },
81
+ async () => {
82
+ if (!existsSync(VIEW_HTML)) {
83
+ throw new Error("the grid view is not built: run `just mcp-elements` and `pnpm run build`");
84
+ }
85
+ return {
86
+ contents: [
87
+ {
88
+ uri: GRID_URI,
89
+ mimeType: RESOURCE_MIME_TYPE,
90
+ text: readFileSync(VIEW_HTML, "utf8"),
91
+ // Everything is inline: no network, no other origin (E40).
92
+ _meta: { ui: { csp: {}, prefersBorder: true } },
93
+ },
94
+ ],
95
+ };
96
+ },
97
+ );
98
+
99
+ registerAppTool(
100
+ server,
101
+ "opengrid_open",
102
+ {
103
+ title: "Open a data grid",
104
+ description: `Opens a source as an interactive, accessible data grid in the chat. Answers with the session, the columns and the number of rows — never the rows themselves. Sources: ${data.names().join(", ")}.`,
105
+ inputSchema: z.object({
106
+ source: z.string().describe("The source to open."),
107
+ view: View.optional(),
108
+ }),
109
+ _meta: { ui: { resourceUri: GRID_URI } },
110
+ },
111
+ guarded(async ({ source, view }) => {
112
+ await data.ready(source);
113
+ const query = data.viewQuery(source, view ?? {});
114
+ const total = await data.count(query);
115
+ const session = sessions.open(source, view ?? {}, query, total);
116
+ return answer(
117
+ {
118
+ sessionId: session.id,
119
+ source,
120
+ title: data.source(source).title,
121
+ columns: columnsOf(data, source),
122
+ total,
123
+ view: session.view,
124
+ revision: session.revision,
125
+ },
126
+ `Opened ${source} as a grid (session ${session.id}): ${summary(session)}.`,
127
+ );
128
+ }),
129
+ );
130
+
131
+ registerAppTool(
132
+ server,
133
+ "opengrid_set_view",
134
+ {
135
+ title: "Set the grid's view",
136
+ description:
137
+ "Filters, sorts, groups or rearranges the grid by setting its whole view. A view naming a column the grid does not have is refused as a whole. Answers with the applied view and the new number of matches; the grid in the chat shows it when it next syncs.",
138
+ inputSchema: z.object({ sessionId: z.string(), view: View }),
139
+ _meta: { ui: { visibility: ["model"] } },
140
+ },
141
+ guarded(async ({ sessionId, view }) => {
142
+ const session = sessionOf(sessions, sessionId);
143
+ const query = data.viewQuery(session.source, view);
144
+ const total = await data.count(query);
145
+ sessions.setView(session, view, query, total);
146
+ return answer({ sessionId, view, total, revision: session.revision }, `${summary(session)}.`);
147
+ }),
148
+ );
149
+
150
+ registerAppTool(
151
+ server,
152
+ "opengrid_describe",
153
+ {
154
+ title: "Describe the grid",
155
+ description:
156
+ "What the reader sees now: the view, the query of the view, the number of matches and how many rows are selected. No rows.",
157
+ inputSchema: z.object({ sessionId: z.string() }),
158
+ _meta: { ui: { visibility: ["model"] } },
159
+ },
160
+ guarded(async ({ sessionId }) => {
161
+ const session = sessionOf(sessions, sessionId);
162
+ return answer(
163
+ {
164
+ sessionId,
165
+ source: session.source,
166
+ columns: columnsOf(data, session.source),
167
+ view: session.view,
168
+ query: session.query,
169
+ total: session.total,
170
+ selected: session.selected.length,
171
+ },
172
+ `${summary(session)}.`,
173
+ );
174
+ }),
175
+ );
176
+
177
+ registerAppTool(
178
+ server,
179
+ "opengrid_selection",
180
+ {
181
+ title: "The selected rows",
182
+ description: `The rows the reader selected, as objects { column: value }, in the grid's order. At most ${SELECTION_LIMIT} by default, ${SELECTION_MAX} at most; more are cut and said.`,
183
+ inputSchema: z.object({
184
+ sessionId: z.string(),
185
+ limit: z.number().int().min(1).max(SELECTION_MAX).optional(),
186
+ }),
187
+ _meta: { ui: { visibility: ["model"] } },
188
+ },
189
+ guarded(async ({ sessionId, limit }) => {
190
+ const session = sessionOf(sessions, sessionId);
191
+ const wanted = session.selected.slice(0, limit ?? SELECTION_LIMIT);
192
+ const rows = [];
193
+ for (const [offset, count] of runsOf(wanted)) {
194
+ rows.push(...rowsOf(await data.execute({ ...session.query, offset, limit: count })));
195
+ }
196
+ const cut = session.selected.length - wanted.length;
197
+ return answer(
198
+ { sessionId, selected: session.selected.length, rows, truncated: cut > 0 },
199
+ cut > 0
200
+ ? `${rows.length} of ${session.selected.length} selected rows (cut at ${wanted.length}; ask with a larger limit, up to ${SELECTION_MAX}).\n${JSON.stringify(rows)}`
201
+ : JSON.stringify(rows),
202
+ );
203
+ }),
204
+ );
205
+
206
+ // App only: the grid's provider. Rows reach the view, never the model.
207
+ registerAppTool(
208
+ server,
209
+ "opengrid_query",
210
+ {
211
+ title: "Rows for the grid",
212
+ description: "Runs one query of the grid in the chat (its window, a count, a group).",
213
+ inputSchema: z.object({ sessionId: z.string(), query: z.record(z.string(), z.unknown()) }),
214
+ _meta: { ui: { visibility: ["app"] } },
215
+ },
216
+ guarded(async ({ sessionId, query }) => {
217
+ const session = sessionOf(sessions, sessionId);
218
+ if (query.source !== session.source) {
219
+ throw new DataError("validation", `the session's source is ${session.source}`, "query.source");
220
+ }
221
+ return { content: [{ type: "text", text: await data.execute(query) }] };
222
+ }),
223
+ );
224
+
225
+ // App only: the reader's changes in, the model's view out (E40).
226
+ registerAppTool(
227
+ server,
228
+ "opengrid_sync",
229
+ {
230
+ title: "Sync the grid",
231
+ description:
232
+ "Reports the reader's change and answers with the session's view and revision. A change made before the model's last view is dropped.",
233
+ inputSchema: z.object({
234
+ sessionId: z.string(),
235
+ revision: z.number().int().min(0),
236
+ change: z
237
+ .object({
238
+ view: z.record(z.string(), z.unknown()).optional(),
239
+ query: z.record(z.string(), z.unknown()).nullable().optional(),
240
+ selected: z.array(z.number().int().min(0)).optional(),
241
+ })
242
+ .optional(),
243
+ }),
244
+ _meta: { ui: { visibility: ["app"] } },
245
+ },
246
+ guarded(async ({ sessionId, revision, change }) => {
247
+ const session = sessionOf(sessions, sessionId);
248
+ // A stale change is dropped; the answer hands the grid the model's view.
249
+ if (change && !sessions.isStale(session, revision)) {
250
+ // The count of a new query is the server's to say, not the view's.
251
+ const query = change.query ?? undefined;
252
+ if (query && query.source !== session.source) {
253
+ throw new DataError("validation", `the session's source is ${session.source}`, "change.query.source");
254
+ }
255
+ const total = query ? await data.count(query) : undefined;
256
+ sessions.readerChanged(session, { ...change, query, total });
257
+ }
258
+ return answer({
259
+ sessionId,
260
+ revision: session.revision,
261
+ origin: session.origin,
262
+ view: session.view,
263
+ total: session.total,
264
+ summary: summary(session),
265
+ });
266
+ }),
267
+ );
268
+ }