Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: add tool manager and create invoke-tool endpoint (#5409)

Joaquin Coromina2bcb027af6e7
diff --git a/frontend/package.json b/frontend/package.json
index b85ab8f20e..55251ee074 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -45,7 +45,7 @@
"@lezer/markdown": "^1.4.3",
"@lezer/python": "^1.1.18",
"@marimo-team/codemirror-ai": "^0.1.11",
- "@marimo-team/codemirror-languageserver": "^1.15.14",
+ "@marimo-team/codemirror-languageserver": "^1.15.15",
"@marimo-team/marimo-api": "file:../openapi",
"@marimo-team/react-slotz": "^0.2.0",
"@mui/material": "^6.4.11",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 5df3d5ae52..e9ba0f9f6e 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -59,7 +59,7 @@ importers:
version: 6.1.2
'@codemirror/view':
specifier: ^6.37.1
- version: 6.37.1
+ version: 6.37.2
'@dagrejs/dagre':
specifier: ^1.1.4
version: 1.1.4
@@ -110,10 +110,10 @@ importers:
version: 1.1.18
'@marimo-team/codemirror-ai':
specifier: ^0.1.11
- version: 0.1.11(@codemirror/[email protected])(@codemirror/[email protected])
+ version: 0.1.11(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/codemirror-languageserver':
- specifier: ^1.15.14
- version: 1.15.14(@codemirror/[email protected])(@codemirror/[email protected])
+ specifier: ^1.15.15
+ version: 1.15.15(@codemirror/[email protected])(@codemirror/[email protected])
'@marimo-team/marimo-api':
specifier: file:../openapi
version: file:../openapi
@@ -212,7 +212,7 @@ importers:
'@replit/codemirror-vim':
specifier: ^6.3.0
- version: 6.3.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
+ version: 6.3.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
'@tailwindcss/typography':
specifier: ^0.5.16
version: 0.5.16([email protected])
@@ -239,16 +239,16 @@ importers:
'@uiw/codemirror-extensions-langs':
specifier: ^4.23.12
- version: 4.23.12(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
+ version: 4.23.12(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
'@uiw/react-codemirror':
specifier: 4.23.10
'@uwdata/flechette':
specifier: ^1.1.2
version: 1.1.2
'@valtown/codemirror-codeium':
specifier: ^1.1.1
- version: 1.1.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
+ version: 1.1.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
'@xterm/addon-attach':
specifier: ^0.11.0
version: 0.11.0(@xterm/[email protected])
@@ -326,7 +326,7 @@ importers:
version: 4.17.21
loro-codemirror:
specifier: ^0.1.6
- version: 0.1.6(@codemirror/[email protected])(@codemirror/[email protected])([email protected])
+ version: 0.1.6(@codemirror/[email protected])(@codemirror/[email protected])([email protected])
loro-crdt:
specifier: ^1.5.4
version: 1.5.4
@@ -356,13 +356,13 @@ importers:
version: 0.27.5
react-arborist:
specifier: ^3.4.3
react-aria-components:
specifier: ^1.8.0
react-codemirror-merge:
specifier: 4.23.10
react-dropzone:
specifier: ^14.3.8
version: 14.3.8([email protected])
@@ -416,7 +416,7 @@ importers:
version: 1.0.7([email protected])
thememirror:
specifier: ^2.0.1
- version: 2.0.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
+ version: 2.0.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
timestring:
specifier: ^7.0.0
version: 7.0.0
@@ -459,7 +459,7 @@ importers:
version: 2.0.0-beta.6
'@codecov/vite-plugin':
specifier: ^1.9.1
'@csstools/postcss-light-dark-function':
specifier: ^2.0.8
version: 2.0.8([email protected])
@@ -486,7 +486,7 @@ importers:
'@storybook/react-vite':
specifier: ^8.6.14
'@swc-jotai/react-refresh':
specifier: ^0.3.0
version: 0.3.0
@@ -504,7 +504,7 @@ importers:
version: 4.17.12
'@types/node':
specifier: ^24.0.0
- version: 24.0.0
+ version: 24.0.3
'@types/react':
specifier: ^19.1.7
version: 19.1.7
@@ -525,10 +525,10 @@ importers:
'@vitejs/plugin-react':
specifier: ^4.5.0
'@vitejs/plugin-react-swc':
specifier: ^3.10.0
autoprefixer:
specifier: ^10.4.21
version: 10.4.21([email protected])
@@ -564,13 +564,13 @@ importers:
version: 54.0.0([email protected])
eslint-plugin-vitest:
specifier: ^0.4.1
jsdom:
specifier: ^24.1.3
version: 24.1.3
msw:
specifier: ^2.10.2
- version: 2.10.2(@types/[email protected])([email protected])
+ version: 2.10.2(@types/[email protected])([email protected])
npm-run-all2:
specifier: ^6.2.6
version: 6.2.6
@@ -609,19 +609,19 @@ importers:
version: 5.8.3
vite:
specifier: ^6.3.2
vite-plugin-top-level-await:
specifier: ^1.5.0
vite-plugin-wasm:
specifier: ^3.4.1
vite-tsconfig-paths:
specifier: ^5.1.4
vitest:
specifier: ^3.1.4
packages:
@@ -1072,8 +1072,8 @@ packages:
'@codemirror/[email protected]':
resolution: {integrity: sha512-F+sH0X16j/qFLMAfbciKTxVOwkdAS336b7AXTKOZhy8BR3eH/RelsnLgLFINrpST63mmN2OuwUt0W2ndUgYwUA==}
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-Qy4CAUwngy/VQkEz0XzMKVRcckQuqLYWKqVpDDDghBe5FSXSqfVrJn49nw3ePZHxRUz4nRmb05Lgi+9csWo4eg==}
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-XD3LdgQpxQs5jhOOZ2HRVT+Rj59O4Suc7g2ULvZ+Yi8eCkickrkZ5JFuoDhs2ST1mNI5zSsNYgR3NGa4OUrbnw==}
'@connectrpc/[email protected]':
resolution: {integrity: sha512-13aO4psFbbm7rdOFGV0De2Za64DY/acMspgloDlcOKzLPPs0yZkhp1OOzAQeiAIr7BM/VOHIA3p8mF0inxCYTA==}
@@ -1643,8 +1643,8 @@ packages:
'@codemirror/state': ^6
'@codemirror/view': ^6
- '@marimo-team/[email protected]':
- resolution: {integrity: sha512-rCf+aBfZmJqBgXmUb4iUyOLShrPEI7vrUIq88JniCcuz8rkudXzdP2aV3JFBoSjI/QkiT9cutBYS6rPSpXP8Iw==}
+ '@marimo-team/[email protected]':
+ resolution: {integrity: sha512-dJCJ0qn6HDNs12Ps4kk67+/ShPKHla9LpbGIsCaIh9SWi7OnWfUTLyCHCMIxS5ROYsDbkzhKknfm4tucKQI9bQ==}
peerDependencies:
'@codemirror/state': ^6
'@codemirror/view': ^6
@@ -3754,8 +3754,8 @@ packages:
resolution: {integrity: sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==}
- '@types/[email protected]':
- resolution: {integrity: sha512-yZQa2zm87aRVcqDyH5+4Hv9KYgSdgwX1rFnGvpbzMaC7YAljmhBET93TPiTd3ObwTL+gSpIzPKg5BqVxdCvxKg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-R4I/kzCYAdRLzfiCabn9hxWfbuHS573x+r0dJMkkzThEa7pbrcDWK+9zu3e7aBOouf+rQAciqPFMnxwr0aWgKg==}
resolution: {integrity: sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==}
@@ -8265,8 +8265,8 @@ packages:
uglify-js:
optional: true
- resolution: {integrity: sha512-UYCvU9YQW2f/Vwl+P0GfhxJxbUGLwd+5QrrGgLajzWAtC/23AX0vcise32kkP7Eu0Wu9VlzzHAXkLObgjQfFlQ==}
+ resolution: {integrity: sha512-+6erLbBm0+LROX2sPXlUYx/ux5PyE9K/a92Wrt6oA+WDAoFTdpHE5tCYCI5PNzq2y8df4rA+QgHLJuR4jNymsg==}
engines: {node: '>=10'}
hasBin: true
@@ -8949,8 +8949,8 @@ packages:
resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-ykKKus8lqlgXX/1WjudpIEjqsafjOTcOJqxnAbMLAu/KCsDCJ6GBtvscewvTkrn24HsnvFwrSCbenFrhtcCsAA==}
+ resolution: {integrity: sha512-yd1RBzSGanHkitROoPFd6qsrxt+oFhg/129YzheDGqeustzX0vTZJZsSsQjVQC4yzBQ56K55XU8gaNCtIzOnTg==}
engines: {node: '>=10.13.0'}
@@ -9600,24 +9600,24 @@ snapshots:
unplugin: 1.16.1
zod: 3.24.3
dependencies:
'@codecov/bundler-plugin-core': 1.9.1
unplugin: 1.16.1
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/common': 1.2.3
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/common': 1.2.3
'@codemirror/[email protected]':
@@ -9657,7 +9657,7 @@ snapshots:
'@codemirror/lang-javascript': 6.2.1
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/common': 1.2.3
'@lezer/css': 1.1.4
'@lezer/html': 1.3.7
@@ -9673,7 +9673,7 @@ snapshots:
'@codemirror/language': 6.11.1
'@codemirror/lint': 6.8.5
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/common': 1.2.3
'@lezer/javascript': 1.4.18
@@ -9710,7 +9710,7 @@ snapshots:
'@codemirror/lang-html': 6.4.7
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/common': 1.2.3
'@lezer/markdown': 1.4.3
@@ -9811,7 +9811,7 @@ snapshots:
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/common': 1.2.3
'@lezer/highlight': 1.2.1
'@lezer/lr': 1.4.2
@@ -9824,21 +9824,21 @@ snapshots:
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
crelt: 1.0.6
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/highlight': 1.2.1
style-mod: 4.1.2
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
crelt: 1.0.6
'@codemirror/[email protected]':
@@ -9849,10 +9849,10 @@ snapshots:
dependencies:
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/highlight': 1.2.1
- '@codemirror/[email protected]':
+ '@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.5.2
crelt: 1.0.6
@@ -10214,17 +10214,17 @@ snapshots:
dependencies:
img-comparison-slider: 8.0.6
- '@inquirer/[email protected](@types/[email protected])':
+ '@inquirer/[email protected](@types/[email protected])':
dependencies:
- '@inquirer/core': 10.1.13(@types/[email protected])
- '@inquirer/type': 3.0.7(@types/[email protected])
+ '@inquirer/core': 10.1.13(@types/[email protected])
+ '@inquirer/type': 3.0.7(@types/[email protected])
optionalDependencies:
- '@types/node': 24.0.0
+ '@types/node': 24.0.3
- '@inquirer/[email protected](@types/[email protected])':
+ '@inquirer/[email protected](@types/[email protected])':
dependencies:
'@inquirer/figures': 1.0.12
- '@inquirer/type': 3.0.7(@types/[email protected])
+ '@inquirer/type': 3.0.7(@types/[email protected])
ansi-escapes: 4.3.2
cli-width: 4.1.0
mute-stream: 2.0.0
@@ -10232,13 +10232,13 @@ snapshots:
wrap-ansi: 6.2.0
yoctocolors-cjs: 2.1.2
optionalDependencies:
- '@types/node': 24.0.0
+ '@types/node': 24.0.3
'@inquirer/[email protected]': {}
- '@inquirer/[email protected](@types/[email protected])':
+ '@inquirer/[email protected](@types/[email protected])':
optionalDependencies:
- '@types/node': 24.0.0
+ '@types/node': 24.0.3
'@internationalized/[email protected]':
dependencies:
@@ -10266,12 +10266,12 @@ snapshots:
wrap-ansi: 8.1.0
wrap-ansi-cjs: [email protected]
dependencies:
glob: 10.4.5
magic-string: 0.27.0
react-docgen-typescript: 2.4.0([email protected])
optionalDependencies:
typescript: 5.8.3
@@ -10434,17 +10434,17 @@ snapshots:
'@marijn/[email protected]': {}
- '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
+ '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
- '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
+ '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@codemirror/autocomplete': 6.18.6
'@codemirror/lint': 6.8.5
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@open-rpc/client-js': 1.8.1
marked: 15.0.11
vscode-languageserver-protocol: 3.17.5
@@ -12448,22 +12448,22 @@ snapshots:
- '@types/react'
- immer
- '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':
+ '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':
dependencies:
'@codemirror/autocomplete': 6.18.6
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/common': 1.2.3
'@lezer/highlight': 1.2.1
'@lezer/lr': 1.4.2
- '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':
+ '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':
dependencies:
'@codemirror/autocomplete': 6.18.6
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/common': 1.2.3
'@lezer/highlight': 1.2.1
'@lezer/lr': 1.4.2
@@ -12472,7 +12472,7 @@ snapshots:
dependencies:
'@codemirror/language': 6.11.1
- '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':
+ '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])':
dependencies:
'@codemirror/autocomplete': 6.18.6
'@codemirror/lang-css': 6.2.1
@@ -12480,19 +12480,19 @@ snapshots:
'@codemirror/lang-javascript': 6.2.1
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@lezer/common': 1.2.3
'@lezer/highlight': 1.2.1
'@lezer/javascript': 1.4.18
'@lezer/lr': 1.4.2
- '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
+ '@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@codemirror/commands': 6.8.1
'@codemirror/language': 6.11.1
'@codemirror/search': 6.5.11
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@rolldown/[email protected]': {}
@@ -12675,13 +12675,13 @@ snapshots:
react: 19.1.0
react-dom: 19.1.0([email protected])
dependencies:
'@storybook/csf-plugin': 8.6.14([email protected])
browser-assert: 1.2.1
storybook: 8.6.14
ts-dedent: 2.2.0
dependencies:
@@ -12742,11 +12742,11 @@ snapshots:
react-dom: 19.1.0([email protected])
storybook: 8.6.14
dependencies:
'@rollup/pluginutils': 5.1.4([email protected])
find-up: 5.0.0
magic-string: 0.30.17
@@ -12756,7 +12756,7 @@ snapshots:
resolve: 1.22.10
storybook: 8.6.14
tsconfig-paths: 4.2.0
optionalDependencies:
'@storybook/test': 8.6.14([email protected])
transitivePeerDependencies:
@@ -13160,7 +13160,7 @@ snapshots:
dependencies:
- '@types/node': 24.0.0
+ '@types/node': 24.0.3
'@types/tough-cookie': 4.0.5
parse5: 7.1.2
@@ -13190,7 +13190,7 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]':
+ '@types/[email protected]':
dependencies:
undici-types: 7.8.0
@@ -13372,7 +13372,7 @@ snapshots:
react: 19.1.0
react-dom: 19.1.0([email protected])
- '@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
+ '@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@codemirror/autocomplete': 6.18.6
'@codemirror/commands': 6.8.1
@@ -13380,9 +13380,9 @@ snapshots:
'@codemirror/lint': 6.8.5
'@codemirror/search': 6.5.11
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
dependencies:
'@codemirror/lang-angular': 0.1.2
'@codemirror/lang-cpp': 6.0.2
@@ -13406,10 +13406,10 @@ snapshots:
'@codemirror/language-data': 6.5.1
'@codemirror/legacy-modes': 6.5.1
'@nextjournal/lang-clojure': 1.0.0
- '@replit/codemirror-lang-csharp': 6.2.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
- '@replit/codemirror-lang-nix': 6.0.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
+ '@replit/codemirror-lang-csharp': 6.2.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
+ '@replit/codemirror-lang-nix': 6.0.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
'@replit/codemirror-lang-solidity': 6.0.1(@codemirror/[email protected])
- '@replit/codemirror-lang-svelte': 6.0.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
+ '@replit/codemirror-lang-svelte': 6.0.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])(@lezer/[email protected])
codemirror-lang-mermaid: 0.5.0
transitivePeerDependencies:
- '@codemirror/autocomplete'
@@ -13421,14 +13421,14 @@ snapshots:
- '@lezer/javascript'
- '@lezer/lr'
dependencies:
'@babel/runtime': 7.27.6
'@codemirror/commands': 6.8.1
'@codemirror/state': 6.5.2
'@codemirror/theme-one-dark': 6.1.2
- '@codemirror/view': 6.37.1
- '@uiw/codemirror-extensions-basic-setup': 4.23.10(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
+ '@codemirror/view': 6.37.2
+ '@uiw/codemirror-extensions-basic-setup': 4.23.10(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
codemirror: 6.0.1
react: 19.1.0
react-dom: 19.1.0([email protected])
@@ -13442,24 +13442,24 @@ snapshots:
'@uwdata/[email protected]': {}
- '@valtown/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
+ '@valtown/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@bufbuild/protobuf': 1.10.0
'@codemirror/autocomplete': 6.18.6
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
'@connectrpc/connect': 1.4.0(@bufbuild/[email protected])
'@connectrpc/connect-web': 1.4.0(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))
dependencies:
'@rolldown/pluginutils': 1.0.0-beta.9
'@swc/core': 1.11.29
transitivePeerDependencies:
- '@swc/helpers'
dependencies:
'@babel/core': 7.27.4
'@babel/plugin-transform-react-jsx-self': 7.25.9(@babel/[email protected])
@@ -13467,7 +13467,7 @@ snapshots:
'@rolldown/pluginutils': 1.0.0-beta.9
'@types/babel__core': 7.20.5
react-refresh: 0.17.0
transitivePeerDependencies:
- supports-color
@@ -13485,14 +13485,14 @@ snapshots:
chai: 5.2.0
tinyrainbow: 2.0.0
dependencies:
'@vitest/spy': 3.1.4
estree-walker: 3.0.3
magic-string: 0.30.17
optionalDependencies:
- msw: 2.10.2(@types/[email protected])([email protected])
+ msw: 2.10.2(@types/[email protected])([email protected])
'@vitest/[email protected]':
dependencies:
@@ -14129,7 +14129,7 @@ snapshots:
'@codemirror/lint': 6.8.5
'@codemirror/search': 6.5.11
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
dependencies:
@@ -15134,13 +15134,13 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@typescript-eslint/utils': 7.15.0([email protected])([email protected])
eslint: 8.57.0
optionalDependencies:
'@typescript-eslint/eslint-plugin': 7.15.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
transitivePeerDependencies:
- supports-color
- typescript
@@ -16068,7 +16068,7 @@ snapshots:
dependencies:
- '@types/node': 24.0.0
+ '@types/node': 24.0.3
merge-stream: 2.0.0
supports-color: 8.1.1
@@ -16297,10 +16297,10 @@ snapshots:
dependencies:
js-tokens: 4.0.0
dependencies:
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
loro-crdt: 1.5.4
@@ -16731,12 +16731,12 @@ snapshots:
dependencies:
'@bundled-es-modules/cookie': 2.0.1
'@bundled-es-modules/statuses': 1.0.1
'@bundled-es-modules/tough-cookie': 0.1.6
- '@inquirer/confirm': 5.1.12(@types/[email protected])
+ '@inquirer/confirm': 5.1.12(@types/[email protected])
'@mswjs/interceptors': 0.39.2
'@open-draft/deferred-promise': 2.2.0
'@open-draft/until': 2.1.0
@@ -17501,10 +17501,10 @@ snapshots:
dependencies:
safe-buffer: 5.2.1
dependencies:
react: 19.1.0
- react-dnd: 14.0.5(@types/[email protected])(@types/[email protected])([email protected])
+ react-dnd: 14.0.5(@types/[email protected])(@types/[email protected])([email protected])
react-dnd-html5-backend: 14.1.0
react-dom: 19.1.0([email protected])
@@ -17595,14 +17595,14 @@ snapshots:
react: 19.1.0
react-dom: 19.1.0([email protected])
dependencies:
'@babel/runtime': 7.27.6
'@codemirror/merge': 6.6.0
'@codemirror/state': 6.5.2
'@codemirror/theme-one-dark': 6.1.2
- '@codemirror/view': 6.37.1
- '@uiw/react-codemirror': 4.23.10(@babel/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])([email protected])([email protected]([email protected]))([email protected])
+ '@codemirror/view': 6.37.2
+ '@uiw/react-codemirror': 4.23.10(@babel/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])([email protected])([email protected]([email protected]))([email protected])
codemirror: 6.0.1
react: 19.1.0
react-dom: 19.1.0([email protected])
@@ -17620,7 +17620,7 @@ snapshots:
dependencies:
dnd-core: 14.0.1
dependencies:
'@react-dnd/invariant': 2.0.0
'@react-dnd/shallowequal': 2.0.0
@@ -17629,7 +17629,7 @@ snapshots:
hoist-non-react-statics: 3.3.2
react: 19.1.0
optionalDependencies:
- '@types/node': 24.0.0
+ '@types/node': 24.0.3
'@types/react': 19.1.7
@@ -18649,12 +18649,12 @@ snapshots:
jest-worker: 27.5.1
schema-utils: 4.3.2
serialize-javascript: 6.0.2
- terser: 5.42.0
+ terser: 5.43.1
webpack: 5.96.1([email protected])
optionalDependencies:
esbuild: 0.25.5
dependencies:
'@jridgewell/source-map': 0.3.6
acorn: 8.15.0
@@ -18663,11 +18663,11 @@ snapshots:
dependencies:
'@codemirror/language': 6.11.1
'@codemirror/state': 6.5.2
- '@codemirror/view': 6.37.1
+ '@codemirror/view': 6.37.2
dependencies:
@@ -19383,13 +19383,13 @@ snapshots:
'@types/unist': 3.0.3
vfile-message: 4.0.2
dependencies:
cac: 6.7.14
debug: 4.4.1
es-module-lexer: 1.7.0
pathe: 2.0.3
transitivePeerDependencies:
- '@types/node'
- jiti
@@ -19404,32 +19404,32 @@ snapshots:
- tsx
- yaml
dependencies:
'@rollup/plugin-virtual': 3.0.2([email protected])
'@swc/core': 1.11.29
uuid: 10.0.0
transitivePeerDependencies:
- '@swc/helpers'
- rollup
dependencies:
dependencies:
debug: 4.4.1
globrex: 0.1.2
tsconfck: 3.1.5([email protected])
optionalDependencies:
transitivePeerDependencies:
- supports-color
- typescript
dependencies:
esbuild: 0.25.5
fdir: 6.4.4([email protected])
@@ -19438,17 +19438,17 @@ snapshots:
rollup: 4.39.0
tinyglobby: 0.2.13
optionalDependencies:
- '@types/node': 24.0.0
+ '@types/node': 24.0.3
fsevents: 2.3.3
jiti: 1.21.7
less: 4.2.0
- terser: 5.42.0
+ terser: 5.43.1
yaml: 2.7.0
dependencies:
'@vitest/expect': 3.1.4
'@vitest/pretty-format': 3.1.4
'@vitest/runner': 3.1.4
'@vitest/snapshot': 3.1.4
@@ -19465,12 +19465,12 @@ snapshots:
tinyglobby: 0.2.13
tinypool: 1.0.2
tinyrainbow: 2.0.0
why-is-node-running: 2.3.0
optionalDependencies:
'@types/debug': 4.1.12
- '@types/node': 24.0.0
+ '@types/node': 24.0.3
jsdom: 24.1.3
transitivePeerDependencies:
- jiti
@@ -19534,7 +19534,7 @@ snapshots:
@@ -19562,7 +19562,7 @@ snapshots:
tapable: 2.2.2
terser-webpack-plugin: 5.3.14([email protected])([email protected]([email protected]))
watchpack: 2.4.4
- webpack-sources: 3.3.2
+ webpack-sources: 3.3.3
transitivePeerDependencies:
- '@swc/core'
- esbuild
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index 932cf3d229..73cfb8f4be 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -46,7 +46,7 @@ import {
import { getCodes } from "@/core/codemirror/copilot/getCodes";
import { aiAtom, aiEnabledAtom, userConfigAtom } from "@/core/config/config";
import type { UserConfig } from "@/core/config/config-schema";
-import { saveUserConfig } from "@/core/network/requests";
+import { invokeAiTool, saveUserConfig } from "@/core/network/requests";
import { useRuntimeManager } from "@/core/runtime/config";
import { ErrorBanner } from "@/plugins/impl/common/error-banner";
import { type ResolvedTheme, useTheme } from "@/theme/useTheme";
@@ -153,16 +153,7 @@ interface ChatMessageProps {
}
const ChatMessage: React.FC<ChatMessageProps> = memo(
- ({
- message,
- index,
- theme,
- onEdit,
- setChatState,
- chatState,
- isStreamingReasoning,
- totalMessages,
- }) => (
+ ({ message, index, theme, onEdit, isStreamingReasoning, totalMessages }) => (
<div
className={cn(
"flex group relative",
@@ -179,7 +170,7 @@ const ChatMessage: React.FC<ChatMessageProps> = memo(
onChange={() => {
// noop
}}
- onSubmit={(e, newValue) => {
+ onSubmit={(_e, newValue) => {
if (!newValue.trim()) {
return;
}
@@ -437,6 +428,7 @@ const ChatPanelBody = () => {
stop,
} = useChat({
id: activeChat?.id,
+ maxSteps: 10,
initialMessages: useMemo(() => {
return activeChat
? activeChat.messages.map(({ role, content, timestamp, parts }) => ({
@@ -449,7 +441,7 @@ const ChatPanelBody = () => {
}, [activeChat]),
keepLastMessageOnError: true,
// Throttle the messages and data updates to 100ms
- experimental_throttle: 100,
+ // experimental_throttle: 100,
api: runtimeManager.getAiURL("chat").toString(),
headers: runtimeManager.headers(),
experimental_prepareRequestBody: (options) => {
@@ -472,9 +464,19 @@ const ChatPanelBody = () => {
),
);
},
- onToolCall: (_toolCall) => {
- // Logger.warn("Tool call:", toolCall);
- // TODO: Handle tool calls
+ onToolCall: async ({ toolCall }) => {
+ try {
+ const response = await invokeAiTool({
+ toolName: toolCall.toolName,
+ arguments: toolCall.args as Record<string, never>,
+ });
+
+ // This response triggers the onFinish callback
+ return response.result || response.error;
+ } catch (error) {
+ Logger.error("Tool call failed:", error);
+ return `Error: ${error instanceof Error ? error.message : String(error)}`;
+ }
},
onError: (error) => {
Logger.error("An error occurred:", error);
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 11e181b4b2..e1f98172a1 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -177,6 +177,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
shutdownSession = throwNotImplemented;
listSecretKeys = throwNotImplemented;
writeSecret = throwNotImplemented;
+ invokeAiTool = throwNotImplemented;
private async putControlRequest(operation: object) {
await this.rpc.proxy.request.bridge({
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index 8c8e1deefe..b6ef30737f 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -382,5 +382,12 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
+ invokeAiTool: async (request) => {
+ return getClient()
+ .POST("/api/ai/invoke_tool", {
+ body: request,
+ })
+ .then(handleResponse);
+ },
};
}
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index ac022e32ac..205f817950 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -83,5 +83,6 @@ export function createStaticRequests(): EditRequests & RunRequests {
getDependencyTree: throwNotInEditMode,
listSecretKeys: throwNotInEditMode,
writeSecret: throwNotInEditMode,
+ invokeAiTool: throwNotInEditMode,
};
}
diff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.ts
index c57cde61dc..d83a97b185 100644
--- a/frontend/src/core/network/requests-toasting.ts
+++ b/frontend/src/core/network/requests-toasting.ts
@@ -61,6 +61,7 @@ export function createErrorToastingRequests(
getDependencyTree: "Failed to get dependency tree",
listSecretKeys: "Failed to fetch secrets",
writeSecret: "Failed to write secret",
+ invokeAiTool: "Failed to invoke AI tool",
};
const handlers = {} as EditRequests & RunRequests;
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index 8107e785a9..59a32e5a04 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -78,4 +78,5 @@ export const {
getDependencyTree,
listSecretKeys,
writeSecret,
+ invokeAiTool,
} = getRequest();
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index b5630be13e..5df43f941f 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -94,6 +94,8 @@ export type WorkspaceFilesResponse = schemas["WorkspaceFilesResponse"];
export type RunningNotebooksResponse = schemas["RunningNotebooksResponse"];
export type OpenTutorialRequest = schemas["OpenTutorialRequest"];
export type TutorialId = OpenTutorialRequest["tutorialId"];
+export type InvokeAiToolRequest = schemas["InvokeAiToolRequest"];
+export type InvokeAiToolResponse = schemas["InvokeAiToolResponse"];
/**
* Requests sent to the BE during run/edit mode.
@@ -179,6 +181,8 @@ export interface EditRequests {
// Secrets requests
listSecretKeys: (request: ListSecretKeysRequest) => Promise<null>;
writeSecret: (request: CreateSecretRequest) => Promise<null>;
+ // AI Tool requests
+ invokeAiTool: (request: InvokeAiToolRequest) => Promise<InvokeAiToolResponse>;
}
export type RequestKey = keyof (EditRequests & RunRequests);
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index fe9c3340ba..1a00fbbdb2 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -529,6 +529,8 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
+ invokeAiTool = throwNotImplemented;
+
private async putControlRequest(operation: object) {
await this.rpc.proxy.request.bridge({
functionName: "put_control_request",
diff --git a/marimo/_ai/_types.py b/marimo/_ai/_types.py
index 9a104b195e..9250fc2f4b 100644
--- a/marimo/_ai/_types.py
+++ b/marimo/_ai/_types.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import abc
import mimetypes
from dataclasses import dataclass
-from typing import Literal, Optional, TypedDict
+from typing import Any, Literal, Optional, TypedDict, Union
class ChatAttachmentDict(TypedDict):
@@ -13,10 +13,37 @@ class ChatAttachmentDict(TypedDict):
name: Optional[str]
+class TextPartDict(TypedDict):
+ type: Literal["text"]
+ text: str
+
+
+class ReasoningPartDict(TypedDict):
+ type: Literal["reasoning"]
+ reasoning: str
+
+
+class ToolInvocationResultDict(TypedDict):
+ state: Literal["result"]
+ result: Any
+ tool_call_id: str
+ tool_name: str
+ step: int
+ args: dict[str, Any]
+
+
+class ToolInvocationPartDict(TypedDict):
+ type: Literal["tool-invocation"]
+ tool_invocation: ToolInvocationResultDict
+
+
class ChatMessageDict(TypedDict):
role: Literal["user", "assistant", "system"]
content: str
attachments: Optional[list[ChatAttachmentDict]]
+ parts: Optional[
+ list[Union[TextPartDict, ReasoningPartDict, ToolInvocationPartDict]]
+ ]
class ChatModelConfigDict(TypedDict, total=False):
@@ -50,6 +77,43 @@ class ChatAttachment:
self.content_type = mimetypes.guess_type(self.url)[0]
+# AI SDK part type definitions (based on actual frontend structure)
+@dataclass
+class TextPart:
+ """Represents a text content part."""
+
+ type: Literal["text"]
+ text: str
+
+
+@dataclass
+class ReasoningPart:
+ """Represents a reasoning content part."""
+
+ type: Literal["reasoning"]
+ reasoning: str
+
+
+@dataclass
+class ToolInvocationResult:
+ """Represents a tool invocation result part from the AI SDK."""
+
+ state: Literal["result"]
+ result: Any
+ tool_call_id: str
+ tool_name: str
+ step: int
+ args: dict[str, Any]
+
+
+@dataclass
+class ToolInvocationPart:
+ """Represents a tool invocation part from the AI SDK."""
+
+ type: Literal["tool-invocation"]
+ tool_invocation: ToolInvocationResult
+
+
@dataclass
class ChatMessage:
"""
@@ -65,6 +129,11 @@ class ChatMessage:
# Optional attachments to the message.
attachments: Optional[list[ChatAttachment]] = None
+ # Optional parts from AI SDK. (see types above)
+ parts: Optional[
+ list[Union[TextPart, ReasoningPart, ToolInvocationPart]]
+ ] = None
+
@dataclass
class ChatModelConfig:
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index e6466b3b5e..4d44e35548 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -188,6 +188,8 @@ def _generate_server_api_schema() -> dict[str, Any]:
models.SuccessResponse,
models.SuccessResponse,
models.UpdateComponentValuesRequest,
+ models.InvokeAiToolRequest,
+ models.InvokeAiToolResponse,
requests.CodeCompletionRequest,
requests.DeleteCellRequest,
requests.ExecuteMultipleRequest,
diff --git a/marimo/_plugins/ui/_impl/chat/utils.py b/marimo/_plugins/ui/_impl/chat/utils.py
index b42249b316..1b84f17211 100644
--- a/marimo/_plugins/ui/_impl/chat/utils.py
+++ b/marimo/_plugins/ui/_impl/chat/utils.py
@@ -1,12 +1,16 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Optional
+from typing import Optional, Union
from marimo._ai._types import (
ChatAttachment,
ChatMessage,
ChatMessageDict,
+ ReasoningPart,
+ TextPart,
+ ToolInvocationPart,
+ ToolInvocationResult,
)
@@ -28,8 +32,45 @@ def from_chat_message_dict(d: ChatMessageDict) -> ChatMessage:
else:
attachments = None
+ # Handle parts
+ parts_dict = d.get("parts", None)
+ parts: Optional[
+ list[Union[TextPart, ReasoningPart, ToolInvocationPart]]
+ ] = None
+ if parts_dict is not None:
+ parts = []
+ for part_dict in parts_dict:
+ if part_dict["type"] == "text":
+ parts.append(TextPart(type="text", text=part_dict["text"]))
+ elif part_dict["type"] == "reasoning":
+ parts.append(
+ ReasoningPart(
+ type="reasoning", reasoning=part_dict["reasoning"]
+ )
+ )
+ elif part_dict["type"] == "tool-invocation":
+ tool_inv = part_dict["tool_invocation"]
+ if tool_inv["state"] == "result":
+ tool_call = ToolInvocationResult(
+ state=tool_inv["state"],
+ tool_call_id=tool_inv["tool_call_id"],
+ tool_name=tool_inv["tool_name"],
+ step=tool_inv["step"],
+ args=tool_inv["args"],
+ result=tool_inv["result"],
+ )
+ parts.append(
+ ToolInvocationPart(
+ type="tool-invocation", tool_invocation=tool_call
+ )
+ )
+ else:
+ # Skip unsupported tool invocation states
+ continue
+
return ChatMessage(
role=d["role"],
content=d["content"],
attachments=attachments,
+ parts=parts,
)
diff --git a/marimo/_server/ai/backend_tools/__init__.py b/marimo/_server/ai/backend_tools/__init__.py
new file mode 100644
index 0000000000..c630d10b22
--- /dev/null
+++ b/marimo/_server/ai/backend_tools/__init__.py
@@ -0,0 +1,8 @@
+# Copyright 2024 Marimo. All rights reserved.
+"""Backend tools for marimo AI system."""
+# from marimo._server.ai.backend_tools.sample_tool import register_sample_tool # Uncomment to enable sample tool
+
+
+def register_all_backend_tools() -> None:
+ """Register all backend tools with the tool manager."""
+ # register_sample_tool() # Uncomment to enable sample tool
diff --git a/marimo/_server/ai/backend_tools/sample_tool.py b/marimo/_server/ai/backend_tools/sample_tool.py
new file mode 100644
index 0000000000..9ac12650b4
--- /dev/null
+++ b/marimo/_server/ai/backend_tools/sample_tool.py
@@ -0,0 +1,266 @@
+# Copyright 2024 Marimo. All rights reserved.
+"""
+SAMPLE BACKEND TOOL - This file is commented out as an example.
+
+This file demonstrates how to create a backend tool for the marimo AI system.
+Backend tools are functions that run on the server and can be called by the AI
+during conversations.
+
+To create your own backend tool:
+1. Copy this file and rename it
+2. Uncomment the code
+3. Modify the tool definition and handler function
+4. Import and register it in __init__.py
+
+Backend tools are useful for:
+- Server-side operations that require access to the filesystem
+- Database queries
+- API calls to external services
+- System information gathering
+- File operations
+"""
+
+# from __future__ import annotations
+#
+# from typing import Any
+#
+# from marimo import _loggers
+# from ..tools import get_tool_manager, Tool
+#
+# LOGGER = _loggers.marimo_logger()
+#
+#
+# def validate_sample_tool_parameters(arguments: dict[str, Any]) -> tuple[bool, str]:
+# """
+# Validate parameters for the sample tool.
+#
+# This function is optional but recommended for robust parameter validation.
+#
+# Args:
+# arguments: The arguments to validate
+#
+# Returns:
+# Tuple of (is_valid, error_message). If is_valid is True, error_message is empty.
+# """
+# # Define valid parameter names and their expected types
+# valid_params = {
+# "message": str,
+# "count": int,
+# "uppercase": bool,
+# }
+#
+# # Check for required parameters
+# required_params = {"message"}
+# missing_params = required_params - set(arguments.keys())
+# if missing_params:
+# error_msg = f"Missing required parameters: {', '.join(missing_params)}"
+# return False, error_msg
+#
+# # Check for unknown parameters
+# unknown_params = set(arguments.keys()) - set(valid_params.keys())
+# if unknown_params:
+# error_msg = f"Unknown parameters: {', '.join(unknown_params)}. Valid parameters are: {', '.join(valid_params.keys())}"
+# return False, error_msg
+#
+# # Validate parameter types
+# for param_name, param_value in arguments.items():
+# expected_type = valid_params[param_name]
+# if not isinstance(param_value, expected_type):
+# error_msg = f"Parameter '{param_name}' must be of type {expected_type.__name__}, got {type(param_value).__name__}"
+# return False, error_msg
+#
+# # Custom validation logic
+# if "count" in arguments and arguments["count"] < 1:
+# return False, "Parameter 'count' must be greater than 0"
+#
+# if "count" in arguments and arguments["count"] > 10:
+# return False, "Parameter 'count' must be 10 or less"
+#
+# # All validation checks passed
+# return True, ""
+#
+#
+# def register_sample_tool() -> None:
+# """Register a sample backend tool that demonstrates the basic pattern."""
+#
+# # Define the tool with its schema
+# sample_tool = Tool(
+# name="sample_backend_tool",
+# description="A sample backend tool that processes text messages. This demonstrates how to create backend tools.",
+# parameters={
+# "type": "object",
+# "properties": {
+# "message": {
+# "type": "string",
+# "description": "The message to process"
+# },
+# "count": {
+# "type": "integer",
+# "description": "Number of times to repeat the message",
+# "default": 1,
+# "minimum": 1,
+# "maximum": 10
+# },
+# "uppercase": {
+# "type": "boolean",
+# "description": "Whether to convert the message to uppercase",
+# "default": False
+# }
+# },
+# "required": ["message"]
+# },
+# source="backend", # This indicates it's a backend tool
+# mode=["ask", "chat"] # Available in both ask and chat modes
+# )
+#
+# def sample_tool_handler(arguments: dict[str, Any]) -> dict[str, Any]:
+# """
+# Handle the sample tool execution.
+#
+# Args:
+# arguments: The validated arguments passed to the tool
+#
+# Returns:
+# Dictionary containing the tool's response
+# """
+# try:
+# # Extract parameters with defaults
+# message = arguments["message"]
+# count = arguments.get("count", 1)
+# uppercase = arguments.get("uppercase", False)
+#
+# # Process the message
+# processed_message = message.upper() if uppercase else message
+# result = [processed_message] * count
+#
+# # Return structured response
+# return {
+# "success": True,
+# "original_message": message,
+# "processed_messages": result,
+# "settings": {
+# "count": count,
+# "uppercase": uppercase
+# },
+# "total_characters": sum(len(msg) for msg in result)
+# }
+#
+# except Exception as e:
+# # Handle errors gracefully
+# LOGGER.error(f"Error in sample tool: {str(e)}")
+# return {
+# "success": False,
+# "error": f"Tool execution failed: {str(e)}"
+# }
+#
+# # Register the tool with the tool manager
+# get_tool_manager().register_backend_tool(
+# sample_tool, # Tool definition
+# sample_tool_handler, # Handler function
+# validate_sample_tool_parameters # Optional validator function
+# )
+#
+# LOGGER.debug("Registered sample backend tool")
+
+
+# ADVANCED EXAMPLE: Tool with file system access
+#
+# def register_file_info_tool() -> None:
+# """Example of a backend tool that accesses the file system."""
+#
+# file_info_tool = Tool(
+# name="get_file_info",
+# description="Get information about files in the current working directory. Only works on the server.",
+# parameters={
+# "type": "object",
+# "properties": {
+# "pattern": {
+# "type": "string",
+# "description": "File pattern to match (e.g., '*.py', '*.md')",
+# "default": "*"
+# },
+# "include_hidden": {
+# "type": "boolean",
+# "description": "Whether to include hidden files",
+# "default": False
+# }
+# },
+# "required": []
+# },
+# source="backend",
+# mode=["ask", "chat"]
+# )
+#
+# def file_info_handler(arguments: dict[str, Any]) -> dict[str, Any]:
+# """Get file information from the server's file system."""
+# import os
+# import glob
+# from pathlib import Path
+#
+# try:
+# pattern = arguments.get("pattern", "*")
+# include_hidden = arguments.get("include_hidden", False)
+#
+# # Get current working directory
+# cwd = os.getcwd()
+#
+# # Find matching files
+# files = glob.glob(pattern, recursive=False)
+#
+# # Filter hidden files if requested
+# if not include_hidden:
+# files = [f for f in files if not f.startswith('.')]
+#
+# # Get file info
+# file_info = []
+# for file_path in files[:20]: # Limit to 20 files
+# try:
+# path = Path(file_path)
+# stat = path.stat()
+# file_info.append({
+# "name": path.name,
+# "size": stat.st_size,
+# "is_file": path.is_file(),
+# "is_dir": path.is_dir(),
+# "modified": stat.st_mtime
+# })
+# except Exception:
+# continue
+#
+# return {
+# "success": True,
+# "working_directory": cwd,
+# "pattern": pattern,
+# "files_found": len(file_info),
+# "files": file_info
+# }
+#
+# except Exception as e:
+# return {
+# "success": False,
+# "error": str(e)
+# }
+#
+# get_tool_manager().register_backend_tool(
+# file_info_tool,
+# file_info_handler
+# )
+
+
+# TO USE THIS SAMPLE TOOL:
+#
+# 1. Uncomment the code above
+# 2. Add this import to __init__.py:
+# from .sample_tool import register_sample_tool
+#
+# 3. Add this to the __all__ list in __init__.py:
+# __all__ = ["register_server_debug_tool", "register_sample_tool"]
+#
+# 4. Add this to the register_all_backend_tools() function in __init__.py:
+# def register_all_backend_tools():
+# register_server_debug_tool()
+# register_sample_tool()
+#
+# 5. Restart the marimo server
+#
+# The AI will then be able to use your tool in conversations!
diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.py
index 096f37dbbc..cff32e6555 100644
--- a/marimo/_server/ai/providers.py
+++ b/marimo/_server/ai/providers.py
@@ -71,8 +71,7 @@ if TYPE_CHECKING:
ChatCompletionChunk,
)
- from marimo._server.ai.tools import Tool
-
+from marimo._server.ai.tools import Tool, get_tool_manager
ResponseT = TypeVar("ResponseT")
StreamT = TypeVar("StreamT")
@@ -229,11 +228,8 @@ def _get_base_url(config: Any, name: str = "") -> Optional[str]:
def _get_tools(mode: CopilotMode) -> list[Tool]:
- if mode == "ask":
- # TODO: add tools
- return []
- else: # manual mode = no tools
- return []
+ tool_manager = get_tool_manager()
+ return tool_manager.get_tools_for_mode(mode)
class CompletionProvider(Generic[ResponseT, StreamT], ABC):
@@ -296,7 +292,7 @@ class CompletionProvider(Generic[ResponseT, StreamT], ABC):
def _create_stream_content(
self, content_data: Union[str, dict[str, Any]], content_type: str
) -> StreamContent:
- """Create type-safe StreamContent tuple."""
+ """Create type-safe StreamContent tuple for format_stream method."""
# String content types
if isinstance(content_data, str):
if content_type == "text":
@@ -732,14 +728,6 @@ class AnthropicProvider(
ToolUseBlock,
)
- # # For content blocks
- # if isinstance(response, TextDelta):
- # return (response.text, "text")
- # if isinstance(response, ThinkingDelta):
- # return (response.thinking, "reasoning")
- # if isinstance(response, InputJSONDelta):
- # return (response.partial_json, "tool_call_delta")
-
# For streaming content
if isinstance(response, RawContentBlockDeltaEvent):
if isinstance(response.delta, TextDelta):
diff --git a/marimo/_server/ai/tools.py b/marimo/_server/ai/tools.py
index 8a0f5fc1a4..6a82ad8a1e 100644
--- a/marimo/_server/ai/tools.py
+++ b/marimo/_server/ai/tools.py
@@ -1,24 +1,274 @@
-# Copyright 2025 Marimo. All rights reserved.
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
from dataclasses import dataclass
-from typing import Any, Literal
+from typing import Any, Callable, Literal, Optional
+from marimo import _loggers
from marimo._config.config import CopilotMode
-ToolSource = Literal["mcp", "local"]
+LOGGER = _loggers.marimo_logger()
+
+# Type aliases for tool system
+FunctionArgs = dict[str, Any]
+ValidationFunction = Callable[[FunctionArgs], tuple[bool, str]]
+
+ToolSource = Literal["mcp", "backend", "frontend"]
@dataclass
class Tool:
+ """Tool definition compatible with ai-sdk-ui format."""
+
name: str
description: str
parameters: dict[str, Any]
- source: ToolSource # special handling for mcp tools
- mode: list[
- CopilotMode
- ] # tools can be made available in more than one mode
+ source: ToolSource
+ mode: list[CopilotMode] # tools can be available in multiple modes
+
+
+@dataclass
+class ToolResult:
+ """Represents the result of a tool invocation."""
+
+ tool_name: str
+ result: Any
+ error: Optional[str] = None
+
+
+class ToolManager:
+ """Centralized manager for all tools (mcp, backend, frontend)."""
+
+ def __init__(self) -> None:
+ """Initialize the tool manager."""
+ self._tools: dict[str, Tool] = {}
+ self._backend_handlers: dict[str, Callable[[FunctionArgs], Any]] = {}
+ self._validation_functions: dict[str, ValidationFunction] = {}
+
+ # Don't register tools in __init__ to avoid circular imports
+ # Tools will be registered when get_tool_manager() is first called
+ LOGGER.info(
+ "ToolManager created (tools will be registered on first access)"
+ )
+
+ def register_backend_tool(
+ self,
+ tool: Tool,
+ handler: Callable[[FunctionArgs], Any],
+ validator: Optional[ValidationFunction] = None,
+ ) -> None:
+ """Register a backend tool with its handler function and optional validator."""
+ if tool.source != "backend":
+ raise ValueError("Tool source must be 'backend'")
+
+ self._tools[tool.name] = tool
+ self._backend_handlers[tool.name] = handler
+ if validator:
+ self._validation_functions[tool.name] = validator
+ LOGGER.debug(f"Registered backend tool: {tool.name}")
+
+ def register_frontend_tool(self, tool: Tool) -> None:
+ """Register a frontend tool (definition only - no handler or validator needed)."""
+ if tool.source != "frontend":
+ raise ValueError("Tool source must be 'frontend'")
+
+ self._tools[tool.name] = tool
+ LOGGER.debug(f"Registered frontend tool: {tool.name}")
+
+ def register_mcp_tool(self, tool: Tool) -> None:
+ """Register an MCP tool (no local handler needed)."""
+ if tool.source != "mcp":
+ raise ValueError("Tool source must be 'mcp'")
+
+ self._tools[tool.name] = tool
+ LOGGER.debug(f"Registered MCP tool: {tool.name}")
+
+ def get_tools_for_mode(self, mode: CopilotMode) -> list[Tool]:
+ """Get all tools available for a specific mode."""
+ return [tool for tool in self._tools.values() if mode in tool.mode]
+
+ def get_tool(self, name: str) -> Optional[Tool]:
+ """Get tool definition by name."""
+ return self._tools.get(name)
+
+ def validate_backend_tool_arguments(
+ self, tool_name: str, arguments: FunctionArgs
+ ) -> tuple[bool, str]:
+ """Validate tool arguments using tool-specific validation function or fallback to basic validation."""
+ tool = self.get_tool(tool_name)
+ if not tool:
+ return False, f"Tool '{tool_name}' not found"
+
+ # Use tool-specific validation function if available
+ if tool_name in self._validation_functions:
+ try:
+ validator = self._validation_functions[tool_name]
+ is_valid, error_message = validator(arguments)
+ if not is_valid:
+ LOGGER.warning(
+ f"Tool-specific validation failed for '{tool_name}': {error_message}"
+ )
+ return is_valid, error_message
+ except Exception as e:
+ error_msg = f"Error in tool-specific validation for '{tool_name}': {str(e)}"
+ LOGGER.error(error_msg)
+ return False, error_msg
+
+ # Fallback to basic validation against parameters schema
+ required_params = tool.parameters.get("required", [])
+
+ # Check required parameters
+ for param in required_params:
+ if param not in arguments:
+ error_msg = f"Missing required parameter '{param}'"
+ LOGGER.warning(
+ f"Basic validation failed for '{tool_name}': {error_msg}"
+ )
+ return False, error_msg
+
+ return True, ""
+
+ def create_system_llm_error(self, error_message: str) -> str:
+ """Create an LLM error message for a tool."""
+ return f"{error_message} Please file a GitHub issue if this problem persists."
+
+ async def invoke_tool(
+ self, tool_name: str, arguments: FunctionArgs
+ ) -> ToolResult:
+ """Invoke a tool by name and return the result."""
+ tool = self.get_tool(tool_name)
+
+ if not tool:
+ available_tools = list(self._tools.keys())
+ return ToolResult(
+ tool_name=tool_name,
+ result=None,
+ error=f"Tool '{tool_name}' not found. Available tools: {', '.join(available_tools)}",
+ )
+
+ if tool.source == "frontend":
+ system_error = f"Frontend tool '{tool_name}' cannot be invoked in the backend. Frontend tools must be executed in the client."
+ LOGGER.error(system_error)
+ return ToolResult(
+ tool_name=tool_name,
+ result=None,
+ error=self.create_system_llm_error(
+ f"Tool '{tool_name}' is a frontend tool and cannot be executed on the server."
+ ),
+ )
+
+ # Validate arguments for backend tools
+ if tool.source == "backend":
+ is_valid, validation_error = self.validate_backend_tool_arguments(
+ tool_name, arguments
+ )
+ if not is_valid:
+ return ToolResult(
+ tool_name=tool_name,
+ result=None,
+ error=f"Invalid arguments for tool '{tool_name}': {validation_error}",
+ )
+
+ try:
+ if tool.source == "backend":
+ # Handle backend tools
+ handler = self._backend_handlers.get(tool_name)
+ if not handler:
+ system_error = (
+ f"No handler found for backend tool '{tool_name}'."
+ )
+ LOGGER.error(system_error)
+ return ToolResult(
+ tool_name=tool_name,
+ result=None,
+ error=self.create_system_llm_error(
+ f"Tool '{tool_name}' cannot be invoked."
+ ),
+ )
+ result = await self._call_handler(handler, arguments)
+
+ elif tool.source == "mcp":
+ # Handle MCP tools
+ result = await self._invoke_mcp_tool(tool_name, arguments)
+
+ else:
+ # Unknown tool source
+ system_error = f"Unknown tool source: {tool.source} for tool {tool_name}. Supported sources are: backend, frontend, mcp."
+ LOGGER.error(system_error)
+ return ToolResult(
+ tool_name=tool_name,
+ result=None,
+ error=self.create_system_llm_error(
+ f"Tool configuration error for tool {tool_name}."
+ ),
+ )
+
+ return ToolResult(tool_name=tool_name, result=result, error=None)
+
+ except Exception as e:
+ error_message = f"Error invoking tool '{tool_name}': {str(e)}"
+ LOGGER.error(error_message)
+ return ToolResult(
+ tool_name=tool_name, result=None, error=str(error_message)
+ )
+
+ async def _call_handler(
+ self,
+ handler: Callable[[FunctionArgs], Any],
+ arguments: FunctionArgs,
+ ) -> Any:
+ """Call a tool handler, handling both sync and async functions."""
+ import asyncio
+ import inspect
+
+ if inspect.iscoroutinefunction(handler):
+ return await handler(arguments)
+ else:
+ # Run sync function in thread pool to avoid blocking
+ return await asyncio.get_event_loop().run_in_executor(
+ None, handler, arguments
+ )
+
+ async def _invoke_mcp_tool(
+ self, tool_name: str, arguments: FunctionArgs
+ ) -> Any:
+ """Invoke an MCP tool via the MCP client."""
+ # TODO: Implement MCP tool invocation
+ # This would interact with the MCP client to call the tool
+ LOGGER.warning(
+ f"MCP tool invocation not yet implemented for '{tool_name}'"
+ )
+ return {
+ "message": f"MCP tool '{tool_name}' called with args: {arguments}"
+ }
+
+ def _register_builtin_tools(self) -> None:
+ """Register built-in backend tools."""
+ # Register all backend tools from the backend_tools package
+ from marimo._server.ai.backend_tools import register_all_backend_tools
+
+ register_all_backend_tools()
+
+ def _discover_mcp_tools(self) -> None:
+ """Discover and register MCP tools."""
+ # TODO: Implement MCP tool discovery
+ # This would connect to MCP servers and get their available tools
+ LOGGER.debug("MCP tool discovery not yet implemented")
+
+
+# Global tool manager instance using lazy initialization to avoid circular imports
+_TOOL_MANAGER: Optional[ToolManager] = None
-# TODO: Add ToolRegistry class to manage tool registration and retrieval
-# TODO: Add ToolManager class to interact with tool registry,
-# tool invoker, and expose tools to providers.py
-# TODO: Add ToolInvoker class to handle calling tools
+def get_tool_manager() -> ToolManager:
+ """Get the global tool manager instance, initializing it if needed."""
+ global _TOOL_MANAGER
+ if _TOOL_MANAGER is None:
+ _TOOL_MANAGER = ToolManager()
+ # Register tools after the manager is created to avoid circular imports
+ _TOOL_MANAGER._register_builtin_tools()
+ _TOOL_MANAGER._discover_mcp_tools()
+ LOGGER.info(
+ f"ToolManager initialized with {len(_TOOL_MANAGER._tools)} tools"
+ )
+ return _TOOL_MANAGER
diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.py
index 0f4f2128cd..9bc49562c7 100644
--- a/marimo/_server/api/endpoints/ai.py
+++ b/marimo/_server/api/endpoints/ai.py
@@ -1,11 +1,16 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from dataclasses import asdict
from typing import TYPE_CHECKING
from starlette.authentication import requires
from starlette.exceptions import HTTPException
-from starlette.responses import PlainTextResponse, StreamingResponse
+from starlette.responses import (
+ JSONResponse,
+ PlainTextResponse,
+ StreamingResponse,
+)
from marimo import _loggers
from marimo._ai._types import ChatMessage
@@ -25,6 +30,7 @@ from marimo._server.ai.providers import (
get_model,
without_wrapping_backticks,
)
+from marimo._server.ai.tools import get_tool_manager
from marimo._server.api.deps import AppState
from marimo._server.api.status import HTTPStatus
from marimo._server.api.utils import parse_request
@@ -33,6 +39,10 @@ from marimo._server.models.completion import (
AiInlineCompletionRequest,
ChatRequest,
)
+from marimo._server.models.models import (
+ InvokeAiToolRequest,
+ InvokeAiToolResponse,
+)
from marimo._server.router import APIRouter
if TYPE_CHECKING:
@@ -230,3 +240,46 @@ async def ai_inline_completion(
content=provider.collect_stream(response),
media_type="text/plain",
)
+
+
[email protected]("/invoke_tool")
+@requires("edit")
+async def invoke_tool(
+ *,
+ request: Request,
+) -> JSONResponse:
+ """
+ requestBody:
+ description: The request body for tool invocation
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/InvokeAiToolRequest"
+ responses:
+ 200:
+ description: Tool invocation result
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/InvokeAiToolResponse"
+ """
+ app_state = AppState(request)
+ app_state.require_current_session()
+
+ body = await parse_request(request, cls=InvokeAiToolRequest)
+
+ # Invoke the tool
+ result = await get_tool_manager().invoke_tool(
+ body.tool_name, body.arguments
+ )
+
+ # Create and return the response
+ response = InvokeAiToolResponse(
+ success=result.error is None,
+ tool_name=result.tool_name,
+ result=result.result,
+ error=result.error,
+ )
+
+ return JSONResponse(content=asdict(response))
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index 9cee06b24c..9ad5a6ff36 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -165,3 +165,16 @@ class SaveUserConfigurationRequest:
@dataclass
class StdinRequest:
text: str
+
+
+@dataclass
+class InvokeAiToolRequest:
+ tool_name: str
+ arguments: dict[str, Any]
+
+
+@dataclass
+class InvokeAiToolResponse(BaseResponse):
+ tool_name: str
+ result: Any
+ error: Optional[str] = None
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 1daa5f7a53..68ba347d85 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -231,6 +231,91 @@ components:
content:
additionalProperties: true
type: object
+ parts:
+ items:
+ oneOf:
+ - properties:
+ text:
+ type: string
+ type:
+ enum:
+ - text
+ type: string
+ required:
+ - type
+ - text
+ type: object
+ - properties:
+ reasoning:
+ type: string
+ type:
+ enum:
+ - reasoning
+ type: string
+ required:
+ - type
+ - reasoning
+ type: object
+ - properties:
+ toolInvocation:
+ oneOf:
+ - properties:
+ args:
+ additionalProperties: {}
+ type: object
+ state:
+ enum:
+ - call
+ - partial-call
+ type: string
+ step:
+ type: integer
+ toolCallId:
+ type: string
+ toolName:
+ type: string
+ required:
+ - state
+ - toolCallId
+ - toolName
+ - step
+ - args
+ type: object
+ - properties:
+ args:
+ additionalProperties: {}
+ type: object
+ result: {}
+ state:
+ enum:
+ - call
+ - partial-call
+ - result
+ type: string
+ step:
+ type: integer
+ toolCallId:
+ type: string
+ toolName:
+ type: string
+ required:
+ - state
+ - result
+ - toolCallId
+ - toolName
+ - step
+ - args
+ type: object
+ type:
+ enum:
+ - tool-invocation
+ type: string
+ required:
+ - type
+ - toolInvocation
+ type: object
+ nullable: true
+ type: array
role:
enum:
- user
@@ -1121,6 +1206,32 @@ components:
required:
- name
type: object
+ InvokeAiToolRequest:
+ properties:
+ arguments:
+ additionalProperties: {}
+ type: object
+ toolName:
+ type: string
+ required:
+ - toolName
+ - arguments
+ type: object
+ InvokeAiToolResponse:
+ properties:
+ error:
+ nullable: true
+ type: string
+ result: {}
+ success:
+ type: boolean
+ toolName:
+ type: string
+ required:
+ - success
+ - toolName
+ - result
+ type: object
JSONType:
oneOf:
- type: string
@@ -2669,6 +2780,22 @@ paths:
schema:
type: string
description: Get AI inline completion for code
+ /api/ai/invoke_tool:
+ post:
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/InvokeAiToolRequest'
+ description: The request body for tool invocation
+ required: true
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/InvokeAiToolResponse'
+ description: Tool invocation result
/api/datasources/preview_column:
post:
requestBody:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index b4359ab5a3..10750c5a21 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -161,6 +161,46 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/ai/invoke_tool": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /** @description The request body for tool invocation */
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["InvokeAiToolRequest"];
+ };
+ };
+ responses: {
+ /** @description Tool invocation result */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["InvokeAiToolResponse"];
+ };
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/datasources/preview_column": {
parameters: {
query?: never;
@@ -2595,6 +2635,46 @@ export interface components {
content: {
[key: string]: unknown;
};
+ parts?:
+ | (
+ | {
+ text: string;
+ /** @enum {string} */
+ type: "text";
+ }
+ | {
+ reasoning: string;
+ /** @enum {string} */
+ type: "reasoning";
+ }
+ | {
+ toolInvocation:
+ | {
+ args: {
+ [key: string]: unknown;
+ };
+ /** @enum {string} */
+ state: "call" | "partial-call";
+ step: number;
+ toolCallId: string;
+ toolName: string;
+ }
+ | {
+ args: {
+ [key: string]: unknown;
+ };
+ result: unknown;
+ /** @enum {string} */
+ state: "call" | "partial-call" | "result";
+ step: number;
+ toolCallId: string;
+ toolName: string;
+ };
+ /** @enum {string} */
+ type: "tool-invocation";
+ }
+ )[]
+ | null;
/** @enum {string} */
role: "user" | "assistant" | "system";
}[];
@@ -2944,6 +3024,18 @@ export interface components {
/** @enum {string} */
name: "interrupted";
};
+ InvokeAiToolRequest: {
+ arguments: {
+ [key: string]: unknown;
+ };
+ toolName: string;
+ };
+ InvokeAiToolResponse: {
+ error?: string | null;
+ result: unknown;
+ success: boolean;
+ toolName: string;
+ };
JSONType:
| string
| number
diff --git a/tests/_ai/test_chat_convert.py b/tests/_ai/test_chat_convert.py
index e8490cd0b5..548b35ca23 100644
--- a/tests/_ai/test_chat_convert.py
+++ b/tests/_ai/test_chat_convert.py
@@ -235,14 +235,107 @@ def test_from_chat_message_dict():
)
assert result_no_attachments.attachments is None
- # Test case 3: Input is already a ChatMessage
- existing_chat_message = ChatMessage(
- role="system", content="System message", attachments=None
+ # Test case 3: ChatMessage with parts
+ message_dict_with_parts = {
+ "role": "assistant",
+ "content": "Here's my response with reasoning.",
+ "parts": [
+ {"type": "text", "text": "This is a text part"},
+ {"type": "reasoning", "reasoning": "This is my reasoning process"},
+ ],
+ }
+
+ result_with_parts = from_chat_message_dict(message_dict_with_parts)
+
+ assert isinstance(result_with_parts, ChatMessage)
+ assert result_with_parts.role == "assistant"
+ assert result_with_parts.content == "Here's my response with reasoning."
+ assert len(result_with_parts.parts) == 2
+ assert result_with_parts.parts[0].type == "text"
+ assert result_with_parts.parts[0].text == "This is a text part"
+ assert result_with_parts.parts[1].type == "reasoning"
+ assert (
+ result_with_parts.parts[1].reasoning == "This is my reasoning process"
+ )
+
+ # Test case 4: ChatMessage with both attachments and parts
+ message_dict_full = {
+ "role": "user",
+ "content": "Complex message with everything.",
+ "attachments": [
+ {
+ "name": "doc.pdf",
+ "content_type": "application/pdf",
+ "url": "http://example.com/doc.pdf",
+ }
+ ],
+ "parts": [{"type": "text", "text": "Additional text content"}],
+ }
+
+ result_full = from_chat_message_dict(message_dict_full)
+
+ assert isinstance(result_full, ChatMessage)
+ assert result_full.role == "user"
+ assert result_full.content == "Complex message with everything."
+ assert len(result_full.attachments) == 1
+ assert result_full.attachments[0].name == "doc.pdf"
+ assert len(result_full.parts) == 1
+ assert result_full.parts[0].type == "text"
+ assert result_full.parts[0].text == "Additional text content"
+
+ # Test case 5: ChatMessage with tool invocation part (result state only)
+ message_dict_tool_result = {
+ "role": "assistant",
+ "content": "Here's the tool result.",
+ "parts": [
+ {
+ "type": "tool-invocation",
+ "tool_invocation": {
+ "state": "result",
+ "result": {"temperature": "72°F", "condition": "sunny"},
+ "tool_call_id": "call_123",
+ "tool_name": "weather_tool",
+ "step": 1,
+ "args": {"location": "New York"},
+ },
+ }
+ ],
+ }
+
+ result_tool_result = from_chat_message_dict(message_dict_tool_result)
+
+ assert isinstance(result_tool_result, ChatMessage)
+ assert result_tool_result.role == "assistant"
+ assert result_tool_result.content == "Here's the tool result."
+ assert len(result_tool_result.parts) == 1
+ assert result_tool_result.parts[0].type == "tool-invocation"
+ assert result_tool_result.parts[0].tool_invocation.state == "result"
+ assert result_tool_result.parts[0].tool_invocation.result == {
+ "temperature": "72°F",
+ "condition": "sunny",
+ }
+ assert (
+ result_tool_result.parts[0].tool_invocation.tool_call_id == "call_123"
+ )
+ assert (
+ result_tool_result.parts[0].tool_invocation.tool_name == "weather_tool"
+ )
+ assert result_tool_result.parts[0].tool_invocation.step == 1
+ assert result_tool_result.parts[0].tool_invocation.args == {
+ "location": "New York"
+ }
+
+ # Test case 6: Existing ChatMessage input (should return as-is)
+ existing_message = ChatMessage(
+ role="user",
+ content="I'm already a ChatMessage object",
+ attachments=None,
+ parts=None,
)
- result_existing = from_chat_message_dict(existing_chat_message)
+ result_existing = from_chat_message_dict(existing_message)
- assert result_existing is existing_chat_message
+ assert result_existing is existing_message # Should return the same object
@pytest.fixture
diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.py
index cc8593ba27..3a718fa464 100644
--- a/tests/_server/api/endpoints/test_ai.py
+++ b/tests/_server/api/endpoints/test_ai.py
@@ -949,3 +949,303 @@ class TestGetFinishReason(unittest.TestCase):
def test_without_wrapping_backticks(chunks: list[str], expected: str) -> None:
result = list(without_wrapping_backticks(iter(chunks)))
assert "".join(result) == expected
+
+
+# Tool invocation tests (provider-agnostic)
+class TestInvokeToolEndpoint:
+ """Tests for the /invoke_tool endpoint."""
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ @patch("marimo._server.api.endpoints.ai.get_tool_manager")
+ def test_invoke_tool_success(
+ client: TestClient, mock_get_tool_manager: Any
+ ) -> None:
+ """Test successful tool invocation."""
+ from marimo._server.ai.tools import ToolResult
+
+ # Mock the tool manager and its response
+ mock_tool_manager = MagicMock()
+ mock_get_tool_manager.return_value = mock_tool_manager
+
+ # Mock successful tool result as a coroutine
+ async def mock_invoke_tool(
+ _tool_name: str, _arguments: dict
+ ) -> ToolResult:
+ return ToolResult(
+ tool_name="test_tool",
+ result={
+ "message": "Tool executed successfully",
+ "data": [1, 2, 3],
+ },
+ error=None,
+ )
+
+ mock_tool_manager.invoke_tool = mock_invoke_tool
+
+ response = client.post(
+ "/api/ai/invoke_tool",
+ headers=HEADERS,
+ json={
+ "tool_name": "test_tool",
+ "arguments": {"param1": "value1", "param2": 42},
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ response_data = response.json()
+
+ # Verify response structure
+ assert response_data["success"] is True
+ assert response_data["tool_name"] == "test_tool"
+ assert response_data["result"] == {
+ "message": "Tool executed successfully",
+ "data": [1, 2, 3],
+ }
+ assert response_data["error"] is None
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ @patch("marimo._server.api.endpoints.ai.get_tool_manager")
+ def test_invoke_tool_with_error(
+ client: TestClient, mock_get_tool_manager: Any
+ ) -> None:
+ """Test tool invocation with error."""
+ from marimo._server.ai.tools import ToolResult
+
+ # Mock the tool manager and its response
+ mock_tool_manager = MagicMock()
+ mock_get_tool_manager.return_value = mock_tool_manager
+
+ # Mock tool result with error as a coroutine
+ async def mock_invoke_tool(
+ _tool_name: str, _arguments: dict
+ ) -> ToolResult:
+ return ToolResult(
+ tool_name="failing_tool",
+ result=None,
+ error="Tool execution failed: Invalid parameter",
+ )
+
+ mock_tool_manager.invoke_tool = mock_invoke_tool
+
+ response = client.post(
+ "/api/ai/invoke_tool",
+ headers=HEADERS,
+ json={
+ "tool_name": "failing_tool",
+ "arguments": {"invalid_param": "bad_value"},
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ response_data = response.json()
+
+ # Verify response structure for error case
+ assert response_data["success"] is False
+ assert response_data["tool_name"] == "failing_tool"
+ assert response_data["result"] is None
+ assert (
+ response_data["error"]
+ == "Tool execution failed: Invalid parameter"
+ )
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ @patch("marimo._server.api.endpoints.ai.get_tool_manager")
+ def test_invoke_tool_not_found(
+ client: TestClient, mock_get_tool_manager: Any
+ ) -> None:
+ """Test tool invocation when tool doesn't exist."""
+ from marimo._server.ai.tools import ToolResult
+
+ # Mock the tool manager and its response
+ mock_tool_manager = MagicMock()
+ mock_get_tool_manager.return_value = mock_tool_manager
+
+ # Mock tool result for non-existent tool as a coroutine
+ async def mock_invoke_tool(
+ _tool_name: str, _arguments: dict
+ ) -> ToolResult:
+ return ToolResult(
+ tool_name="nonexistent_tool",
+ result=None,
+ error="Tool 'nonexistent_tool' not found. Available tools: get_server_debug_info",
+ )
+
+ mock_tool_manager.invoke_tool = mock_invoke_tool
+
+ response = client.post(
+ "/api/ai/invoke_tool",
+ headers=HEADERS,
+ json={"tool_name": "nonexistent_tool", "arguments": {}},
+ )
+
+ assert response.status_code == 200, response.text
+ response_data = response.json()
+
+ # Verify response structure for not found case
+ assert response_data["success"] is False
+ assert response_data["tool_name"] == "nonexistent_tool"
+ assert response_data["result"] is None
+ assert "not found" in response_data["error"]
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ @patch("marimo._server.api.endpoints.ai.get_tool_manager")
+ def test_invoke_tool_validation_error(
+ client: TestClient, mock_get_tool_manager: Any
+ ) -> None:
+ """Test tool invocation with validation error."""
+ from marimo._server.ai.tools import ToolResult
+
+ # Mock the tool manager and its response
+ mock_tool_manager = MagicMock()
+ mock_get_tool_manager.return_value = mock_tool_manager
+
+ # Mock tool result with validation error as a coroutine
+ async def mock_invoke_tool(
+ _tool_name: str, _arguments: dict
+ ) -> ToolResult:
+ return ToolResult(
+ tool_name="test_tool",
+ result=None,
+ error="Invalid arguments for tool 'test_tool': Missing required parameter 'required_param'",
+ )
+
+ mock_tool_manager.invoke_tool = mock_invoke_tool
+
+ response = client.post(
+ "/api/ai/invoke_tool",
+ headers=HEADERS,
+ json={
+ "tool_name": "test_tool",
+ "arguments": {"optional_param": "value"},
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ response_data = response.json()
+
+ # Verify response structure for validation error
+ assert response_data["success"] is False
+ assert response_data["tool_name"] == "test_tool"
+ assert response_data["result"] is None
+ assert "Invalid arguments" in response_data["error"]
+ assert "required_param" in response_data["error"]
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ @patch("marimo._server.api.endpoints.ai.get_tool_manager")
+ def test_invoke_tool_complex_arguments(
+ client: TestClient, mock_get_tool_manager: Any
+ ) -> None:
+ """Test tool invocation with complex argument types."""
+ from marimo._server.ai.tools import ToolResult
+
+ # Mock the tool manager and its response
+ mock_tool_manager = MagicMock()
+ mock_get_tool_manager.return_value = mock_tool_manager
+
+ # Mock successful tool result with complex data as a coroutine
+ async def mock_invoke_tool(
+ _tool_name: str, _arguments: dict
+ ) -> ToolResult:
+ return ToolResult(
+ tool_name="complex_tool",
+ result={
+ "processed_data": [
+ {"id": 1, "value": "a"},
+ {"id": 2, "value": "b"},
+ ],
+ "summary": {"total": 2, "success": True},
+ "metadata": {"timestamp": "2024-01-01T00:00:00Z"},
+ },
+ error=None,
+ )
+
+ mock_tool_manager.invoke_tool = mock_invoke_tool
+
+ complex_args = {
+ "string_param": "test string",
+ "number_param": 42,
+ "boolean_param": True,
+ "array_param": [1, 2, 3, "four"],
+ "object_param": {
+ "nested_string": "nested value",
+ "nested_number": 3.14,
+ "nested_array": ["a", "b", "c"],
+ },
+ }
+
+ response = client.post(
+ "/api/ai/invoke_tool",
+ headers=HEADERS,
+ json={"tool_name": "complex_tool", "arguments": complex_args},
+ )
+
+ assert response.status_code == 200, response.text
+ response_data = response.json()
+
+ # Verify response structure
+ assert response_data["success"] is True
+ assert response_data["tool_name"] == "complex_tool"
+ assert "processed_data" in response_data["result"]
+ assert "summary" in response_data["result"]
+ assert "metadata" in response_data["result"]
+ assert response_data["error"] is None
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ def test_invoke_tool_without_session(client: TestClient) -> None:
+ """Test tool invocation without valid session."""
+ response = client.post(
+ "/api/ai/invoke_tool",
+ headers={
+ "Authorization": "Bearer fake-token"
+ }, # No session header
+ json={"tool_name": "test_tool", "arguments": {}},
+ )
+
+ # Should fail without proper session
+ assert response.status_code in [400, 401, 403], response.text
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ @patch("marimo._server.api.endpoints.ai.get_tool_manager")
+ def test_invoke_tool_empty_arguments(
+ client: TestClient, mock_get_tool_manager: Any
+ ) -> None:
+ """Test tool invocation with empty arguments."""
+ from marimo._server.ai.tools import ToolResult
+
+ # Mock the tool manager and its response
+ mock_tool_manager = MagicMock()
+ mock_get_tool_manager.return_value = mock_tool_manager
+
+ # Mock successful tool result with empty arguments
+ async def mock_invoke_tool(
+ tool_name: str, _arguments: dict
+ ) -> ToolResult:
+ return ToolResult(
+ tool_name=tool_name,
+ result={"message": "Tool executed with empty args"},
+ error=None,
+ )
+
+ mock_tool_manager.invoke_tool = mock_invoke_tool
+
+ response = client.post(
+ "/api/ai/invoke_tool",
+ headers=HEADERS,
+ json={
+ "tool_name": "test_tool",
+ "arguments": {}, # Empty arguments
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ data = response.json()
+ assert data["tool_name"] == "test_tool"
+ assert data["result"]["message"] == "Tool executed with empty args"
+ assert data["error"] is None