@datagrok/grokky 1.0.4 → 1.1.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.
Files changed (203) hide show
  1. package/.claude/skills/deploy-grokky/SKILL.md +193 -0
  2. package/.grokignore +2 -0
  3. package/.turbo/turbo-build.log +24 -0
  4. package/.vscode/settings.json +16 -0
  5. package/CHANGELOG.md +151 -8
  6. package/CLAUDE.md +284 -0
  7. package/CREDITS.md +173 -0
  8. package/LICENSE.md +16 -0
  9. package/README.md +24 -0
  10. package/bdd/bdd.config.json +1 -0
  11. package/bdd/bindings/elements.ts +9 -0
  12. package/bdd/bindings/steps.ts +787 -0
  13. package/bdd/features/ai-panel/platform-work.feature +63 -0
  14. package/bdd/features/ai-panel/session.feature +69 -0
  15. package/bdd/features/ai-panel/table-work.feature +99 -0
  16. package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
  17. package/bdd/generated/ai-panel/session.test.ts +100 -0
  18. package/bdd/generated/ai-panel/table-work.test.ts +150 -0
  19. package/bdd/package.json +1 -0
  20. package/bdd/tsconfig.json +13 -0
  21. package/css/ai.css +637 -49
  22. package/dist/package-test.js +4 -1707
  23. package/dist/package-test.js.map +1 -1
  24. package/dist/package.js +742 -92317
  25. package/dist/package.js.map +1 -1
  26. package/dockerfiles/claude-runtime/.dockerignore +1 -0
  27. package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
  28. package/dockerfiles/claude-runtime/Dockerfile +73 -13
  29. package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
  30. package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
  31. package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
  32. package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
  33. package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
  34. package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
  35. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
  36. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
  37. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
  38. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
  39. package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
  40. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
  41. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
  42. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
  43. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
  44. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
  45. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
  46. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
  47. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
  48. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
  49. package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
  50. package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
  51. package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
  52. package/dockerfiles/claude-runtime/container.json +2 -2
  53. package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
  54. package/dockerfiles/claude-runtime/package-lock.json +1721 -306
  55. package/dockerfiles/claude-runtime/package.json +20 -5
  56. package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
  57. package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
  58. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
  59. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
  60. package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
  61. package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
  62. package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
  63. package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
  64. package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
  65. package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
  66. package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
  67. package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
  68. package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
  69. package/dockerfiles/claude-runtime/pyproject.toml +18 -0
  70. package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
  71. package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
  72. package/dockerfiles/claude-runtime/src/constants.ts +20 -0
  73. package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
  74. package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
  75. package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
  76. package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
  77. package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
  78. package/dockerfiles/claude-runtime/src/server.ts +134 -234
  79. package/dockerfiles/claude-runtime/src/session.ts +328 -0
  80. package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
  81. package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
  82. package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
  83. package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
  84. package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
  85. package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
  86. package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
  87. package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
  88. package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
  89. package/dockerfiles/claude-runtime/src/types.ts +142 -23
  90. package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
  91. package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
  92. package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
  93. package/dockerfiles/claude-runtime/src/verify.ts +136 -0
  94. package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
  95. package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
  96. package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
  97. package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
  98. package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
  99. package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
  100. package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
  101. package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
  102. package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
  103. package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
  104. package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
  105. package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
  106. package/dockerfiles/mcp-server/.eslintrc.json +39 -0
  107. package/dockerfiles/mcp-server/Dockerfile +10 -2
  108. package/dockerfiles/mcp-server/package-lock.json +1743 -98
  109. package/dockerfiles/mcp-server/package.json +27 -5
  110. package/dockerfiles/mcp-server/src/api-client.ts +123 -66
  111. package/dockerfiles/mcp-server/src/format.ts +51 -0
  112. package/dockerfiles/mcp-server/src/index.ts +44 -113
  113. package/dockerfiles/mcp-server/src/ops.ts +325 -0
  114. package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
  115. package/dockerfiles/mcp-server/test/format.test.js +62 -0
  116. package/dockerfiles/mcp-server/test/ops.test.js +84 -0
  117. package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
  118. package/dockerfiles/queue/Dockerfile +2 -0
  119. package/dockerfiles/queue/container.json +7 -0
  120. package/docs/AUDIT-2026-08-03.md +1064 -0
  121. package/docs/BENCHMARK.md +292 -0
  122. package/docs/CLAUDE_CODE_FLOW.md +746 -0
  123. package/docs/EXAMPLES.md +82 -0
  124. package/docs/FEATURES.md +71 -0
  125. package/docs/IMPLEMENTATION.md +128 -0
  126. package/docs/LATENCY.md +170 -0
  127. package/docs/VISION.md +36 -0
  128. package/files/benchmark/suite.yaml +404 -0
  129. package/files/scripts/process-cro-results.md +14 -0
  130. package/files/suggestions.yaml +344 -0
  131. package/package.json +39 -97
  132. package/src/ai/ai-window.ts +157 -0
  133. package/src/ai/benchmark/benchmark.ts +737 -0
  134. package/src/ai/db-view-functions.ts +56 -0
  135. package/src/ai/engine.ts +98 -0
  136. package/src/ai/gemma-engine.ts +81 -0
  137. package/src/ai/panel.ts +1385 -0
  138. package/src/ai/prompt-suggestions.ts +209 -0
  139. package/src/ai/search/combined-search.ts +244 -0
  140. package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
  141. package/src/{llm-utils → ai}/storage.ts +0 -1
  142. package/src/ai/table-tools.ts +145 -0
  143. package/src/ai/ui.ts +720 -0
  144. package/src/ai/usage-limiter.ts +105 -0
  145. package/src/ai/view-tools.ts +352 -0
  146. package/src/claude/ai-feature.ts +16 -0
  147. package/src/claude/exec-blocks.ts +176 -0
  148. package/src/claude/queue-task.ts +84 -0
  149. package/src/claude/runtime-client.ts +310 -0
  150. package/src/claude/turn-log.ts +114 -0
  151. package/src/claude/undoable.ts +105 -0
  152. package/src/{llm-utils → db}/db-index-tools.ts +24 -32
  153. package/src/db/sql-tools.ts +336 -0
  154. package/src/depr/LLM-client.ts +251 -0
  155. package/src/depr/ai-panel.ts +174 -0
  156. package/src/depr/chatgpt-assistant.ts +257 -0
  157. package/src/depr/creds.ts +30 -0
  158. package/src/depr/deepwikiclient.ts +118 -0
  159. package/src/depr/indexes/dg-repository-index.ts +266 -0
  160. package/src/depr/interfaces.ts +170 -0
  161. package/src/depr/is-help-request.ts +39 -0
  162. package/src/depr/prompt-engine.ts +52 -0
  163. package/src/depr/rendering-tools.ts +103 -0
  164. package/src/depr/script-tools.ts +785 -0
  165. package/src/depr/tableview-tools.ts +746 -0
  166. package/src/depr/viewers-ai.ts +67 -0
  167. package/src/package-api.ts +87 -28
  168. package/src/package-test.ts +1 -0
  169. package/src/package.g.ts +98 -48
  170. package/src/package.ts +211 -157
  171. package/src/polyfills.ts +12 -0
  172. package/src/utils.ts +128 -0
  173. package/tsconfig.json +8 -70
  174. package/webpack.config.js +3 -49
  175. package/.eslintignore +0 -2
  176. package/src/ai-panel.ts +0 -174
  177. package/src/claude-code/claude-panel.ts +0 -34
  178. package/src/claude-code/claude-runtime-client.ts +0 -148
  179. package/src/llm-utils/LLM-client.ts +0 -251
  180. package/src/llm-utils/combined-search.ts +0 -162
  181. package/src/llm-utils/creds.ts +0 -30
  182. package/src/llm-utils/deepwikiclient.ts +0 -118
  183. package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
  184. package/src/llm-utils/panel.ts +0 -866
  185. package/src/llm-utils/script-tools.ts +0 -784
  186. package/src/llm-utils/sql-tools.ts +0 -840
  187. package/src/llm-utils/tableview-tools.ts +0 -704
  188. package/src/llm-utils/ui.ts +0 -315
  189. package/src/prompt-engine/chatgpt-assistant.ts +0 -257
  190. package/src/prompt-engine/interfaces.ts +0 -170
  191. package/src/prompt-engine/prompt-engine.ts +0 -52
  192. package/src/prompt-engine/rendering-tools.ts +0 -103
  193. package/src/prompts/is-help-request.ts +0 -26
  194. package/src/viewers-ai.ts +0 -67
  195. /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
  196. /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
  197. /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
  198. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
  199. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
  200. /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
  201. /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
  202. /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
  203. /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
@@ -5,11 +5,33 @@
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "bin": { "datagrok-mcp": "dist/index.js" },
8
- "scripts": { "start": "node dist/index.js", "build": "tsc" },
8
+ "scripts": {
9
+ "start": "node dist/index.js",
10
+ "build": "tsc",
11
+ "lint": "eslint \"src/**/*.ts\" \"test/*.js\"",
12
+ "lint-fix": "eslint \"src/**/*.ts\" \"test/*.js\" --fix",
13
+ "test": "tsc && node --test test/"
14
+ },
9
15
  "dependencies": {
10
- "@modelcontextprotocol/sdk": "^1.21.1",
11
- "@hono/node-server": "^1.13.0",
12
- "hono": "^4.6.0"
16
+ "@modelcontextprotocol/sdk": "^1.32.2",
17
+ "@hono/node-server": "^2.1.6",
18
+ "hono": "^4.13.16"
19
+ },
20
+ "overrides": {
21
+ "body-parser": "^2.4.0",
22
+ "express-rate-limit": "^8.2.2",
23
+ "fast-uri": "^3.1.4",
24
+ "path-to-regexp": "^8.4.0",
25
+ "proxy-addr": "^2.0.8",
26
+ "qs": "^6.17.1",
27
+ "ip-address": "^10.7.6"
13
28
  },
14
- "devDependencies": { "@types/node": "^20.3.1", "typescript": "^5.1.3" }
29
+ "devDependencies": {
30
+ "@types/node": "^20.3.1",
31
+ "@typescript-eslint/eslint-plugin": "^8.67.0",
32
+ "@typescript-eslint/parser": "^8.67.0",
33
+ "eslint": "^8.57.1",
34
+ "eslint-config-google": "^0.14.0",
35
+ "typescript": "^5.1.3"
36
+ }
15
37
  }
@@ -1,100 +1,157 @@
1
- import {AsyncLocalStorage} from 'node:async_hooks';
1
+ import {randomUUID} from 'node:crypto';
2
2
 
3
- interface RequestContext {
4
- apiKey: string;
5
- apiUrl: string;
3
+ export {runWithContext, request, toGrokPath, listFiles, downloadFile, uploadFile} from './shared-api-client.js';
4
+ import {request} from './shared-api-client.js';
5
+
6
+ export function listFunctions(filter?: string): Promise<unknown[]> {
7
+ const qs = filter ? `?text=${encodeURIComponent(filter)}` : '';
8
+ return request('GET', `/public/v1/functions${qs}`);
9
+ }
10
+
11
+ export function getFunction(id: string): Promise<unknown> {
12
+ const name = id.replace(/:/g, '.');
13
+ return request('GET', `/public/v1/functions/${name}`);
14
+ }
15
+
16
+ export function callFunction(name: string, params?: Record<string, unknown>): Promise<unknown> {
17
+ return request('POST', `/public/v1/functions/${name.replace(/:/g, '.')}/call`, params ?? {});
18
+ }
19
+
20
+ export function saveFunction(data: Record<string, unknown>): Promise<unknown> {
21
+ return request('POST', '/public/v1/functions', data);
6
22
  }
7
23
 
8
- const ctxStore = new AsyncLocalStorage<RequestContext>();
24
+ export function getCurrentUser(): Promise<unknown> {
25
+ return request('GET', '/public/v1/users/current');
26
+ }
9
27
 
10
- function _ctx(): RequestContext {
11
- const ctx = ctxStore.getStore();
12
- if (!ctx)
13
- throw new Error('No request context — missing x-user-api-key / x-datagrok-api-url headers');
14
- return ctx;
28
+ export function listConnections(filter?: string): Promise<unknown[]> {
29
+ const qs = filter ? `?text=${encodeURIComponent(filter)}` : '';
30
+ return request('GET', `/public/v1/connections${qs}`);
15
31
  }
16
32
 
17
- export function runWithContext<T>(ctx: RequestContext, fn: () => T): T {
18
- return ctxStore.run(ctx, fn);
33
+ export function listGroups(filter?: string): Promise<unknown[]> {
34
+ const qs = filter ? `?text=${encodeURIComponent(filter)}` : '';
35
+ return request('GET', `/public/v1/groups${qs}`);
36
+ }
37
+
38
+ export function listUsers(filter?: string): Promise<unknown[]> {
39
+ const qs = filter ? `?text=${encodeURIComponent(filter)}` : '';
40
+ return request('GET', `/public/v1/users${qs}`);
41
+ }
42
+
43
+ // --- Projects ---
44
+
45
+ export function listProjects(filter?: string): Promise<unknown[]> {
46
+ const qs = filter ? `?text=${encodeURIComponent(filter)}` : '';
47
+ return request('GET', `/projects${qs}`);
19
48
  }
20
49
 
21
- interface Connection {
22
- id: string;
23
- name: string;
50
+ export function getProject(id: string): Promise<unknown> {
51
+ return request('GET', `/projects/${id}`);
24
52
  }
25
53
 
26
- function toGrokPath(name: string): string {
27
- return name.replace(/:/g, '.');
54
+ export function createProject(name: string, description?: string): Promise<unknown> {
55
+ return request('POST', '/projects', {id: randomUUID(), name, description: description ?? ''});
28
56
  }
29
57
 
30
- async function request<T = unknown>(
31
- method: string, path: string, body?: unknown, headers?: Record<string, string>,
32
- ): Promise<T> {
33
- const ctx = _ctx();
34
- const url = `${ctx.apiUrl}/${path.replace(/^\//, '')}`;
35
- const res = await fetch(url, {
36
- method,
37
- headers: {
38
- 'Content-Type': 'application/json',
39
- 'Authorization': ctx.apiKey,
40
- ...headers,
41
- },
42
- body: body !== undefined ? JSON.stringify(body) : undefined,
58
+ export function deleteProject(id: string): Promise<unknown> {
59
+ return request('DELETE', `/projects/${id}`);
60
+ }
61
+
62
+ export function searchProject(name: string): Promise<unknown[]> {
63
+ return request('GET', `/projects/search?name=${encodeURIComponent(name)}`);
64
+ }
65
+
66
+ export function listRecentProjects(): Promise<unknown[]> {
67
+ return request('GET', '/projects/recent');
68
+ }
69
+
70
+ export function attachEntityToProject(
71
+ projectId: string, entityId: string, link: boolean = false,
72
+ ): Promise<unknown> {
73
+ return request('POST', '/projects/relations', {
74
+ id: randomUUID(),
75
+ project: {id: projectId},
76
+ entity: {id: entityId},
77
+ isLink: link,
43
78
  });
79
+ }
44
80
 
45
- if (!res.ok) {
46
- const text = await res.text();
47
- throw new Error(`HTTP ${res.status}: ${text}`);
48
- }
49
- if (res.headers.has('api-error')) {
50
- const text = await res.text();
51
- throw new Error(`API error: ${text}`);
52
- }
81
+ export function shareProject(
82
+ projectId: string, groups: string[], access: 'View' | 'Edit' = 'View',
83
+ ): Promise<unknown> {
84
+ const name = encodeURIComponent(projectId.replace(/:/g, '.'));
85
+ const qs = new URLSearchParams({groups: groups.join(','), access}).toString();
86
+ return request('POST', `/public/v1/entities/${name}/shares?${qs}`);
87
+ }
53
88
 
54
- const ct = res.headers.get('content-type') ?? '';
55
- if (ct.includes('application/json'))
56
- return res.json();
57
- return res.text() as T;
89
+ export function listProjectShares(projectId: string): Promise<unknown[]> {
90
+ return request('GET', `/privileges/permissions?entityId=${encodeURIComponent(projectId)}`);
58
91
  }
59
92
 
60
- export function listFunctions(filter?: string): Promise<unknown[]> {
93
+ // --- Spaces ---
94
+
95
+ export function listSpaces(filter?: string): Promise<unknown[]> {
61
96
  const qs = filter ? `?text=${encodeURIComponent(filter)}` : '';
62
- return request('GET', `/public/v1/functions${qs}`);
97
+ return request('GET', `/spaces${qs}`);
63
98
  }
64
99
 
65
- export function getFunction(id: string): Promise<unknown> {
66
- return request('GET', `/public/v1/functions/${toGrokPath(id)}`);
100
+ export function getSpace(id: string): Promise<unknown> {
101
+ return request('GET', `/spaces/${id}`);
67
102
  }
68
103
 
69
- export function callFunction(name: string, params?: Record<string, unknown>): Promise<unknown> {
70
- return request('POST', `/public/v1/functions/${toGrokPath(name)}/call`, params ?? {});
104
+ // A space is a project the platform marks as one; without these fields the server stores a plain project
105
+ // (core SpacesClient.createRootSpace / SpaceClient.addSubspace).
106
+ function space(friendlyName: string, isRoot: boolean): Record<string, unknown> {
107
+ const name = friendlyName.trim().replace(/^[^A-Za-z]+/, '').split(/[^A-Za-z0-9]+/).filter(Boolean)
108
+ .map((w) => w[0].toUpperCase() + w.slice(1)).join('');
109
+ return {name, friendlyName, isRoot, isDashboard: false};
71
110
  }
72
111
 
73
- export function saveFunction(data: Record<string, unknown>): Promise<unknown> {
74
- return request('POST', '/public/v1/functions', data);
112
+ export function createRootSpace(name: string): Promise<unknown> {
113
+ return request('POST', '/spaces', space(name, true));
114
+ }
115
+
116
+ export function deleteSpace(id: string): Promise<unknown> {
117
+ return request('DELETE', `/spaces/${id}`);
118
+ }
119
+
120
+ export function createSubspace(spaceId: string, name: string, link?: boolean): Promise<unknown> {
121
+ const qs = link ? '?link=true' : '';
122
+ return request('POST', `/spaces/${spaceId}/subspaces${qs}`, space(name, false));
75
123
  }
76
124
 
77
- export async function listFiles(connector: string, path?: string): Promise<unknown[]> {
78
- const searchName = connector.includes(':') ? connector.split(':').pop()! : connector;
79
- const conns = await request<Connection[]>(
80
- 'GET', `/public/v1/connections?text=${encodeURIComponent(searchName)}`,
81
- );
82
- if (!conns.length)
83
- throw new Error(`Connection "${connector}" not found`);
84
- const filePath = path ? `${path.replace(/^\//, '')}/` : '';
85
- return request('GET', `/connectors/connections/${conns[0].id}/files/${filePath}`);
125
+ export function listSpaceChildren(
126
+ spaceId: string, types?: string, includeLinked?: boolean,
127
+ ): Promise<unknown[]> {
128
+ const params = new URLSearchParams();
129
+ if (types)
130
+ params.set('types', types);
131
+ if (includeLinked !== undefined)
132
+ params.set('includeLinked', String(includeLinked));
133
+ const qs = params.toString() ? `?${params}` : '';
134
+ return request('GET', `/spaces/${spaceId}/children${qs}`);
86
135
  }
87
136
 
88
- export function downloadFile(connector: string, path: string): Promise<unknown> {
89
- return request('GET', `/public/v1/files/${toGrokPath(connector)}/${path}`, undefined,
90
- {'Accept': 'application/octet-stream'});
137
+ export function addEntityToSpace(spaceId: string, entityId: string, link?: boolean): Promise<unknown> {
138
+ const qs = link ? '?link=true' : '';
139
+ return request('POST', `/spaces/${spaceId}/entities/${entityId}${qs}`);
91
140
  }
92
141
 
93
- export function uploadFile(connector: string, path: string, content: string): Promise<unknown> {
94
- return request('POST', `/public/v1/files/${toGrokPath(connector)}/${path}`, content,
142
+ export function removeEntityFromSpace(spaceId: string, entityId: string): Promise<unknown> {
143
+ return request('DELETE', `/spaces/${spaceId}/entities/${entityId}`);
144
+ }
145
+
146
+ export function readSpaceFile(spaceId: string, path: string): Promise<unknown> {
147
+ return request('GET', `/spaces/${spaceId}/files/${path.replace(/^\//, '')}`);
148
+ }
149
+
150
+ export function writeSpaceFile(spaceId: string, path: string, content: string): Promise<unknown> {
151
+ return request('POST', `/spaces/${spaceId}/files/${path.replace(/^\//, '')}`, content,
95
152
  {'Content-Type': 'application/octet-stream'});
96
153
  }
97
154
 
98
- export function getCurrentUser(): Promise<unknown> {
99
- return request('GET', '/public/v1/users/current');
155
+ export function deleteSpaceFile(spaceId: string, path: string): Promise<unknown> {
156
+ return request('DELETE', `/spaces/${spaceId}/files/${path.replace(/^\//, '')}`);
100
157
  }
@@ -0,0 +1,51 @@
1
+ // Tool-result shaping. A tool result is not a one-off cost: it stays in the transcript and is
2
+ // re-read on every later hop of the turn, so an unpaged pretty-printed list taxes the whole turn
3
+ // (LATENCY.md Tier 4). Results are therefore compact JSON, array results are paged, and everything
4
+ // is capped — a naive `list` on a large instance used to inject hundreds of KB mid-turn.
5
+
6
+ export type ToolResult = {content: {type: 'text'; text: string}[]; isError?: boolean};
7
+
8
+ const DEFAULT_LIMIT = 50;
9
+ const MAX_CHARS = 20_000;
10
+ const MAX_RAW_CHARS = 40_000;
11
+ const MAX_ERROR_CHARS = 2_000;
12
+
13
+ const wrap = (text: string): ToolResult => ({content: [{type: 'text', text}]});
14
+
15
+ function cap(text: string, max: number): string {
16
+ return text.length <= max ? text :
17
+ `${text.slice(0, max)}\n…truncated at ${max} chars — narrow the filter or use limit/offset`;
18
+ }
19
+
20
+ export interface FormatOpts {
21
+ paged?: boolean;
22
+ raw?: boolean;
23
+ args?: Record<string, any>;
24
+ }
25
+
26
+ export function formatResult(data: unknown, opts: FormatOpts = {}): ToolResult {
27
+ if (typeof data === 'string')
28
+ return wrap(cap(data, opts.raw ? MAX_RAW_CHARS : MAX_CHARS));
29
+
30
+ let payload = data;
31
+ if (opts.paged && Array.isArray(data)) {
32
+ const offset = Number(opts.args?.offset) || 0;
33
+ const limit = Number(opts.args?.limit) || DEFAULT_LIMIT;
34
+ const items = data.slice(offset, offset + limit);
35
+ payload = items.length < data.length ?
36
+ {total: data.length, showing: `${offset + 1}-${offset + items.length}`,
37
+ note: 'pass offset/limit for more', items} :
38
+ items;
39
+ }
40
+ return wrap(cap(JSON.stringify(payload), opts.raw ? MAX_RAW_CHARS : MAX_CHARS));
41
+ }
42
+
43
+ /** Errors come back as a result, not a throw: the model can read and correct them in-place,
44
+ * whereas a protocol-level error ends the tool call with nothing actionable in it. */
45
+ export function formatError(message: string, detail?: unknown): ToolResult {
46
+ const error = message.length <= MAX_ERROR_CHARS ? message :
47
+ `${message.slice(0, MAX_ERROR_CHARS)}…truncated at ${MAX_ERROR_CHARS} chars`;
48
+ const result = wrap(JSON.stringify(detail === undefined ? {error} : {error, ...(detail as object)}));
49
+ result.isError = true;
50
+ return result;
51
+ }
@@ -4,133 +4,63 @@ import {McpServer} from '@modelcontextprotocol/sdk/server/mcp.js';
4
4
  import {WebStandardStreamableHTTPServerTransport} from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
5
5
  import {z} from 'zod/v4';
6
6
  import * as api from './api-client.js';
7
+ import {DOMAINS, catalog, opMenu, missingParams, confirmTokenFor, type Domain} from './ops.js';
8
+ import {formatResult, formatError} from './format.js';
7
9
 
8
10
  const PORT = 3003;
9
11
 
10
- type ToolResult = {content: {type: 'text'; text: string}[]};
11
-
12
- function formatResult(data: unknown): ToolResult {
13
- const text = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
14
- return {content: [{type: 'text', text}]};
15
- }
16
-
17
- async function runTool(
18
- name: string, args: Record<string, unknown>, fn: () => Promise<unknown>,
19
- ): Promise<ToolResult> {
20
- const tag = `[MCP] ${name}(${JSON.stringify(args)})`;
12
+ async function runOp(d: Domain, op: string | undefined, args: Record<string, unknown>) {
13
+ // No op named: the model is asking what this domain can do. Cheaper than putting every
14
+ // signature in the prompt prefix, and it is the documented way to get parameter details.
15
+ if (!op)
16
+ return formatResult(catalog(d));
17
+ const spec = d.ops[op];
18
+ if (!spec)
19
+ return formatError(`unknown op '${op}' for ${d.tool}`, {available: Object.keys(d.ops)});
20
+ const missing = missingParams(spec, args);
21
+ if (missing.length)
22
+ return formatError(`missing required parameter(s): ${missing.join(', ')}`, catalog(d));
23
+
24
+ const tag = `[MCP] ${d.tool}.${op}(${JSON.stringify(args)})`;
21
25
  const startMs = Date.now();
22
26
  console.log(`${tag} ...`);
23
27
  try {
24
- const result = formatResult(await fn());
25
- const len = result.content[0]?.text.length ?? 0;
26
- console.log(`${tag} OK ${len} chars in ${Date.now() - startMs}ms`);
28
+ if (spec.preview) {
29
+ const {confirm, ...rest} = args;
30
+ const token = confirmTokenFor(d.tool, op, rest);
31
+ if (confirm !== token) {
32
+ return formatResult({
33
+ dryRun: true, wouldDelete: await spec.preview(rest), confirmToken: token,
34
+ note: 'Nothing was deleted. Ask the user for approval (via the datagrok_confirm tool ' +
35
+ 'when available — it displays the summary, so do not restate it in text); repeat the ' +
36
+ 'call with `confirm` only after they approve.',
37
+ });
38
+ }
39
+ }
40
+ const result = formatResult(await spec.run(args), {paged: !spec.raw, raw: spec.raw, args});
41
+ console.log(`${tag} OK ${result.content[0]?.text.length ?? 0} chars in ${Date.now() - startMs}ms`);
27
42
  return result;
28
43
  } catch (e: any) {
29
44
  console.error(`${tag} FAILED in ${Date.now() - startMs}ms: ${e.message ?? e}`);
30
- throw e;
45
+ return formatError(e.message ?? String(e));
31
46
  }
32
47
  }
33
48
 
34
49
  function createServer(): McpServer {
35
50
  const server = new McpServer({name: 'datagrok', version: '1.0.0'});
36
51
 
37
- server.tool(
38
- 'list_functions', 'List Datagrok functions with optional smart filter',
39
- {filter: z.string().optional().describe('Smart search filter (e.g. source="script")')},
40
- ({filter}) => runTool('list_functions', {filter}, () => api.listFunctions(filter)),
41
- );
42
-
43
- server.tool(
44
- 'get_function', 'Get detailed information about a function',
45
- {id: z.string().describe('Function ID or name (e.g. "Namespace:FuncName")')},
46
- ({id}) => runTool('get_function', {id}, () => api.getFunction(id)),
47
- );
48
-
49
- server.tool(
50
- 'call_function', 'Execute a Datagrok function',
51
- {
52
- name: z.string().describe('Name of the function (e.g. "Namespace:FuncName")'),
53
- params: z.record(z.string(), z.unknown()).optional()
54
- .describe('Parameters to pass to the function'),
55
- },
56
- ({name, params}) => runTool('call_function', {name, params},
57
- () => api.callFunction(name, params)),
58
- );
59
-
60
- server.tool(
61
- 'list_scripts', 'List all scripts', {},
62
- () => runTool('list_scripts', {}, () => api.listFunctions('source="script"')),
63
- );
64
-
65
- server.tool(
66
- 'list_queries', 'List all data queries', {},
67
- () => runTool('list_queries', {}, () => api.listFunctions('source="data-query"')),
68
- );
69
-
70
- server.tool(
71
- 'create_script', 'Create a new script in Datagrok',
72
- {
73
- script: z.string().describe('Script source code'),
74
- name: z.string().optional().describe('Script name'),
75
- language: z.string().optional()
76
- .describe('Script language (python, r, julia, nodejs, grok, octave). Defaults to python'),
77
- },
78
- ({script, name, language}) => runTool('create_script', {name, language}, () => api.saveFunction({
79
- source: 'script', script,
80
- name: name ?? 'Untitled Script',
81
- language: language ?? 'python',
82
- })),
83
- );
84
-
85
- server.tool(
86
- 'create_query', 'Create a new data query in Datagrok',
87
- {
88
- connectionId: z.string().describe('ID of the data connection'),
89
- query: z.string().describe('SQL query text'),
90
- name: z.string().optional().describe('Query name'),
91
- },
92
- ({connectionId, query, name}) => runTool('create_query', {connectionId, name}, () => api.saveFunction({
93
- source: 'data-query', query,
94
- connection: {id: connectionId},
95
- name: name ?? 'Untitled Query',
96
- })),
97
- );
98
-
99
- server.tool(
100
- 'list_files', 'List files in a connector directory',
101
- {
102
- connector: z.string().describe('Connector name (e.g. "System:DemoFiles")'),
103
- path: z.string().optional().describe('Directory path within the connector'),
104
- },
105
- ({connector, path}) => runTool('list_files', {connector, path},
106
- () => api.listFiles(connector, path)),
107
- );
108
-
109
- server.tool(
110
- 'download_file', 'Download a file from a connector',
111
- {
112
- connector: z.string().describe('Connector name (e.g. "System:DemoFiles")'),
113
- path: z.string().describe('File path within the connector'),
114
- },
115
- ({connector, path}) => runTool('download_file', {connector, path},
116
- () => api.downloadFile(connector, path)),
117
- );
118
-
119
- server.tool(
120
- 'upload_file', 'Upload content to a file in a connector',
121
- {
122
- connector: z.string().describe('Connector name (e.g. "System:DemoFiles")'),
123
- path: z.string().describe('File path within the connector'),
124
- content: z.string().describe('File content to upload'),
125
- },
126
- ({connector, path, content}) => runTool('upload_file', {connector, path},
127
- () => api.uploadFile(connector, path, content)),
128
- );
129
-
130
- server.tool(
131
- 'whoami', 'Get current authenticated user info', {},
132
- () => runTool('whoami', {}, () => api.getCurrentUser()),
133
- );
52
+ for (const d of DOMAINS) {
53
+ server.tool(
54
+ d.tool,
55
+ `${d.blurb} Use this tool, not source code or raw HTTP, for these operations. ` +
56
+ 'Call it as {op: "<name>", args: {<parameters>}}; `?` marks an optional parameter.\n' + opMenu(d),
57
+ {
58
+ op: z.string().optional().describe(`One of: ${Object.keys(d.ops).join(', ')}.`),
59
+ args: z.record(z.string(), z.unknown()).optional().describe('Arguments for the chosen operation.'),
60
+ },
61
+ ({op, args}) => runOp(d, op, (args ?? {}) as Record<string, unknown>),
62
+ );
63
+ }
134
64
 
135
65
  return server;
136
66
  }
@@ -152,4 +82,5 @@ app.all('/mcp', async (c) => {
152
82
  });
153
83
 
154
84
  serve({fetch: app.fetch, port: PORT});
155
- console.log(`datagrok-mcp listening on :${PORT}`);
85
+ console.log(`datagrok-mcp listening on :${PORT} — ${DOMAINS.length} domain tools, ` +
86
+ `${DOMAINS.reduce((n, d) => n + Object.keys(d.ops).length, 0)} operations`);