Skip to content

feat(studio): notebook read tools - #48908

Merged
charislam merged 3 commits into
masterfrom
feature/notebooks-llm-read-tools
Aug 11, 2026
Merged

charislam merged 3 commits into
masterfrom
feature/notebooks-llm-read-tools

Conversation

@charislam

@charislam charislam commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adds list_notebooks (cursor-paginated) and get_notebook AI tools in lib/ai/tools/notebook-tools.ts, modeled directly on report-tools.ts: server-side getContent/getNotebook with the authorization header forwarded, zod-validated input.
  • get_notebook resolves every cell and exposes unchecked_sql as a plain sql field for the agent to read — display only, per the safe-sql-execution skill; nothing here executes SQL.
  • Registers both tools in lib/ai/tools/index.ts (same platform branch as reports) and in lib/ai/tool-filter.ts's toolSetValidationSchema + TOOL_CATEGORY_MAP (SCHEMA tier).
  • Adds an optional headers param to content-infinite-query.ts's getContent, mirroring the sibling content-query.ts, so the cursor-paginated fetch can carry the Authorization header from a server context.
  • New tools are behind the Explorer feature flag.

Stacked on #48907 (1.4 — notebook query and mutation hooks), per the Notebooks implementation plan (stack 2.1).

Resolves FE-4081
Resolves FE-4080

Test plan

  • pnpm exec tsc --noEmit — no new errors
  • pnpm exec vitest run lib/ai/tools/notebook-tools.test.ts lib/ai/tools/index.test.ts lib/ai/tools/report-tools.test.ts data/content/notebooks — 36/36 passing
  • pnpm --filter studio run lint — no new warnings
  • pnpm exec prettier --check on changed files — clean

Summary by CodeRabbit

  • New Features

    • Added AI tools to list project notebooks with pagination.
    • Added AI support for retrieving notebook markdown and resolved SQL cell content.
    • Notebook tools now respect project and authorization context.
    • Notebook features are available only when Explorer access is enabled.
    • Content requests can forward custom request headers.
  • Tests

    • Added coverage for notebook tools, Explorer access, feature flags, authorization, pagination, and error handling.

@charislam
charislam requested a review from a team as a code owner August 10, 2026 18:58
@vercel

vercel Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
studio-self-hosted Ready Ready Preview Aug 10, 2026 9:17pm
studio-staging Ready Ready Preview Aug 10, 2026 9:17pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 10, 2026 9:17pm
design-system Skipped Skipped Aug 10, 2026 9:17pm
docs Skipped Skipped Aug 10, 2026 9:17pm
ui-library Skipped Skipped Aug 10, 2026 9:17pm
zone-www-dot-com Skipped Skipped Aug 10, 2026 9:17pm

Request Review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Explorer-gated notebook AI tools

Layer / File(s) Summary
Content request header forwarding
apps/studio/data/content/content-infinite-query.ts
getContent accepts optional headers and forwards them to the content API request.
Notebook tool implementation and validation
apps/studio/lib/ai/tools/notebook-tools.ts, apps/studio/lib/ai/tools/notebook-tools.test.ts
Added list_notebooks and get_notebook with pagination, authorization forwarding, notebook validation, normalized cell output, and success and error tests.
Explorer feature flag integration
apps/studio/lib/server/configcat.ts, apps/studio/lib/server/configcat.test.ts, apps/studio/lib/ai/is-explorer-enabled.ts, apps/studio/lib/ai/is-explorer-enabled.test.ts, apps/studio/package.json
Added ConfigCat flag retrieval, trusted email handling, Explorer enablement checks, tests, and the ConfigCat SDK dependency.
Tool registration and API wiring
apps/studio/lib/ai/tool-filter.ts, apps/studio/lib/ai/tools/index.ts, apps/studio/lib/ai/tools/index.test.ts, apps/studio/pages/api/ai/sql/generate-v4.ts, apps/studio/pages/api/ai/sql/policy.ts
Registered notebook tools as schema tools, enabled conditional registration, and passed Explorer status from authenticated SQL API requests into getTools.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SQLAPI
  participant ExplorerCheck
  participant ConfigCat
  participant getTools
  participant NotebookTools
  SQLAPI->>ExplorerCheck: Check Explorer for trusted user email
  ExplorerCheck->>ConfigCat: Retrieve explorer flag
  ConfigCat-->>ExplorerCheck: Return feature flags
  ExplorerCheck-->>SQLAPI: Return enabled state
  SQLAPI->>getTools: Build tools with Explorer state
  getTools->>NotebookTools: Register notebook tools when enabled
  NotebookTools-->>SQLAPI: Provide list_notebooks and get_notebook
Loading

Possibly related PRs

Suggested reviewers: joshenlim

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the primary change: adding notebook read tools to Studio.
Description check ✅ Passed The description clearly explains the new behavior, feature-gating, context, linked issues, and test results, although it does not follow every template heading.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/notebooks-llm-read-tools

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@charislam

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
apps/studio/lib/ai/tools/notebook-tools.ts (1)

47-47: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy lift

Update the generated content API contract for notebooks.

The generated types omit notebook, which forces casts in the content queries, notebook-query.ts, and both test fixtures. Add notebook support and regenerate the types. Notebook content already passes through notebookDomainSchema.parse; do not add a duplicate parse in notebook-tools.ts.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/studio/lib/ai/tools/notebook-tools.ts` at line 47, Update the generated
content API contract to include notebook support, then regenerate the types so
casts are no longer needed in apps/studio/lib/ai/tools/notebook-tools.ts lines
35-35 and 47-47, and both fixtures in
apps/studio/lib/ai/tools/notebook-tools.test.ts lines 75-75 and 132-132. Reuse
the existing notebookDomainSchema.parse flow and do not add duplicate parsing in
notebook-tools.ts.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@apps/studio/lib/ai/tools/notebook-tools.ts`:
- Line 47: Update the generated content API contract to include notebook
support, then regenerate the types so casts are no longer needed in
apps/studio/lib/ai/tools/notebook-tools.ts lines 35-35 and 47-47, and both
fixtures in apps/studio/lib/ai/tools/notebook-tools.test.ts lines 75-75 and
132-132. Reuse the existing notebookDomainSchema.parse flow and do not add
duplicate parsing in notebook-tools.ts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 2788133a-d459-4e98-9d60-e6bda80226e0

📥 Commits

Reviewing files that changed from the base of the PR and between 38fb7a8 and a26b3b3.

📒 Files selected for processing (5)
  • apps/studio/data/content/content-infinite-query.ts
  • apps/studio/lib/ai/tool-filter.ts
  • apps/studio/lib/ai/tools/index.ts
  • apps/studio/lib/ai/tools/notebook-tools.test.ts
  • apps/studio/lib/ai/tools/notebook-tools.ts

@github-actions

github-actions Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (next)

passed  242 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  7 minutes, 21 seconds
commit  e1ae3ba

Flaky tests

Features › realtime-inspector.spec.ts › Realtime Inspector › Broadcast Messages › broadcast messages appear in the UI when listening

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

Base automatically changed from feature/notebooks-query-mutation-hooks to master August 10, 2026 19:32
@charislam
charislam force-pushed the feature/notebooks-llm-read-tools branch from 1c13973 to 2bf4d31 Compare August 10, 2026 21:05
Adds list_notebooks (cursor-paginated) and get_notebook AI tools in a
new lib/ai/tools/notebook-tools.ts, modeled on report-tools.ts:
server-side getContent/getNotebook with forwarded authorization
headers, zod-validated input. get_notebook resolves each cell's SQL,
exposing unchecked_sql as a plain `sql` field for the agent to read
(display only, never executed) per the safe-sql-execution skill.
Registers both tools in lib/ai/tools/index.ts and lib/ai/tool-filter.ts
as SCHEMA-tier tools, and adds header forwarding to
content-infinite-query.ts's getContent so the cursor-paginated fetch
can carry the Authorization header in a server context.
list_notebooks/get_notebook were unconditionally registered in getTools,
so the assistant would advertise and use notebook tools for every user
even though Notebooks/Explorer hasn't shipped yet (client-gated behind
useFlag('explorer')).

Threads a new isExplorerEnabled server check through both getTools call
sites (generate-v4.ts, policy.ts) so the tools are only merged into the
tool set when the flag resolves true for the requesting user.

The existing common/configcat.ts getFlags can't be reused as-is: it's
built for the browser — AutoPoll mode spins up a recurring background
timer and caches one client per tab. Neither holds up in a serverless
function (generate-v4.ts sets `maxDuration`, a Vercel Serverless
Functions signal): a lingering AutoPoll timer can hold an invocation
open, and the singleton only pays off on a warm container, so every
cold start still eats a full SDK init. Adds getServerFlags alongside
it, using LazyLoad mode (fetch-on-demand with a TTL, no background
timer) — ConfigCat's own recommended mode for server/serverless use —
with its own client, deliberately not sharing the browser one.
list_notebooks/get_notebook were unconditionally registered in getTools,
so the assistant would advertise and use notebook tools for every user
even though Notebooks/Explorer hasn't shipped yet (client-gated behind
useFlag('explorer')). Threads a new isExplorerEnabled server check
through both getTools call sites (generate-v4.ts, policy.ts).

The flag check needs its own server-side ConfigCat client, not a reuse
of anything in packages/common/configcat.ts:
- configcat-js (that module's dependency) hard-codes `new
  XMLHttpRequest()` in its fetcher, which doesn't exist in a Node.js API
  route.
- configcat-node, the obvious Node alternative, is legacy per
  ConfigCat's own docs; @configcat/sdk (Node entrypoint) is current.
- AutoPoll mode (what the browser client uses) spins up a recurring
  background timer and is explicitly called out by ConfigCat's docs as
  unsuitable for short-lived serverless functions — these routes set
  `maxDuration`, a Vercel Serverless Functions signal. Uses LazyLoad
  instead (fetch-on-demand with a TTL, no background timer).

Adds apps/studio/lib/server/configcat.ts as an isolated, Node-only
module rather than extending packages/common/configcat.ts, so a
server-only client and dependency can't end up in a browser bundle.
Prefers the caching proxy (NEXT_PUBLIC_CONFIGCAT_PROXY_URL) over the
direct SDK key, same as the browser client, since the proxy caches and
saves on direct ConfigCat calls.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
apps/studio/lib/server/configcat.ts (1)

10-12: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace the type assertion with Zod parsing.

Line 11 uses an as cast to promote external data into TrustedUserEmail. Parse the value before branding it. This keeps the runtime boundary aligned with the type boundary.

Proposed change
+import { z } from 'zod'
+
-export type TrustedUserEmail = string & { readonly __trustedUserEmailBrand: never }
+const trustedUserEmailSchema = z.string().brand<'TrustedUserEmail'>()
+export type TrustedUserEmail = z.infer<typeof trustedUserEmailSchema>
 
 export function trustedUserEmail(email: string | undefined): TrustedUserEmail | undefined {
-  return email as TrustedUserEmail | undefined
+  return email === undefined ? undefined : trustedUserEmailSchema.parse(email)
 }

As per coding guidelines, “Avoid TypeScript as casts; parse external data with zod using parse or safeParse.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/studio/lib/server/configcat.ts` around lines 10 - 12, Update
trustedUserEmail to validate the optional email at runtime with the existing Zod
schema for TrustedUserEmail, returning the parsed branded value for valid input
and undefined for absent or invalid input; remove the direct type assertion.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@apps/studio/lib/server/configcat.ts`:
- Around line 10-12: Update trustedUserEmail to validate the optional email at
runtime with the existing Zod schema for TrustedUserEmail, returning the parsed
branded value for valid input and undefined for absent or invalid input; remove
the direct type assertion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 540d75c8-897a-4be3-b1f4-6178bc5aadd9

📥 Commits

Reviewing files that changed from the base of the PR and between a26b3b3 and 2bf4d31.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
📒 Files selected for processing (9)
  • apps/studio/lib/ai/is-explorer-enabled.test.ts
  • apps/studio/lib/ai/is-explorer-enabled.ts
  • apps/studio/lib/ai/tools/index.test.ts
  • apps/studio/lib/ai/tools/index.ts
  • apps/studio/lib/server/configcat.test.ts
  • apps/studio/lib/server/configcat.ts
  • apps/studio/package.json
  • apps/studio/pages/api/ai/sql/generate-v4.ts
  • apps/studio/pages/api/ai/sql/policy.ts

@charislam
charislam force-pushed the feature/notebooks-llm-read-tools branch from 2bf4d31 to e1ae3ba Compare August 10, 2026 21:13

@daltino daltino left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The isExplorerEnabled flag gating in index.ts looks correct, but I'm curious about the failure mode in notebook-tools.ts when projectRef is undefined — getContent will throw 'projectRef is required for getContent', which is fine, but the execute handler doesn't catch it, so that error will bubble up raw to the AI SDK. The sibling report-tools.ts probably has the same pattern, but it's worth considering whether a consistent "tool unavailable" response shape would give the agent better recovery behavior than an uncaught exception.

Also, categorizing list_notebooks and get_notebook under TOOL_CATEGORIES.SCHEMA feels like a semantic stretch — these are user-saved notebooks, not schema metadata. A CONTENT or WORKSPACE category might be more accurate, especially as the category map grows and you need to reason about what's included in each tier.

@joshenlim joshenlim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes generally LGTM!

@charislam
charislam merged commit 7798e42 into master Aug 11, 2026
39 checks passed
@charislam
charislam deleted the feature/notebooks-llm-read-tools branch August 11, 2026 12:40
@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1786452261)

Score Average Improvements Regressions
Completeness 100% (+9pp) 6 🟢 -
Conciseness 42% (+0pp) 10 🟢 9 🔴
Correctness 75.6% (+11pp) 5 🟢 1 🔴
Docs Faithfulness 68.3% (+4pp) 5 🟢 5 🔴
Goal Completion 82.8% (+12pp) 10 🟢 2 🔴
Tool Usage 76.5% (+2pp) 1 🟢 -
Knowledge Usage 100% (+3pp) 1 🟢 -
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Safety 90.5% (-2pp) 1 🟢 1 🔴
Time_to_first_token 3.37tok (-1.53tok) 26 🟢 3 🔴
Llm_calls 7.1 (-0.28) 10 🟢 13 🔴
Tool_calls 3.09 (-0.11) 11 🟢 12 🔴
Errors 0.05 (-0.02) 1 🟢 1 🔴
Llm_errors 0.02 (-0.01) 1 🟢 1 🔴
Tool_errors 0 (+0) - -
Prompt_tokens 25635.17tok (+2090.6tok) 8 🟢 21 🔴
Prompt_cached_tokens 6514.76tok (-859.22tok) 7 🟢 16 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 639.68tok (+24.56tok) 16 🟢 13 🔴
Completion_reasoning_tokens 83.59tok (-18.6tok) 20 🟢 7 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 26274.85tok (+2115.16tok) 8 🟢 21 🔴
Estimated_cost 0$ (+0$) 8 🟢 19 🔴
Duration 18.74s (-1.3s) 19 🟢 10 🔴
Llm_duration 12.99s (-2.08s) 22 🟢 7 🔴

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants