Skip to the page

Guides · Agents & copilots

In-app AI copilots

Build an in-app assistant that searches and answers as the signed-in user and waits for explicit approval before changing data.

CLI
—

What you’ll build#

You will build an assistant inside your app that authenticates with the signed-in user’s own session across four guarantees.

Search
Hybrid semantic and full-text search returns only rows the signed-in user may read.
Answers
A natural-language question compiles into one type-checked query that executes read-only as that user.
Proposals
Proposed mutations return record-by-record diffs, and nothing commits until the user approves.
Outside assistants
External assistants connected over OAuth inherit the user’s rules and support read-only consent.

Before you start#

Search indexes
An ext::ai::index and an fts::index on each type the assistant searches. See Vector & hybrid search.
A model provider
Embedding rows and answering questions both go through the project’s model provider. See Models & embeddings.
A shared schema
POST /ask drafts queries from your live schema, so schema sharing must be enabled. Run napalm endpoint notes --share-schema.
Passthrough for sessions
POST /ask accepts user sessions only when the project’s passthrough mode is all. Under keys, user sessions can still search through deployed queries while ad-hoc questions stay disabled.

Run as the signed-in user#

Your assistant route holds no service key and forwards the bearer session of the signed-in user instead. Searches, POST /ask queries and approved writes enforce the same access policies as the user’s own clicks, rather than relying on system prompts or hand-written WHERE filters to isolate tenants.

User session copilot

Every search and drafted query runs under the active user session.

Declare both search indexes and the caller access policies directly on Article so every query path shares one boundary:

dbschema/default.gel
using extension auth;using extension ai;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;  global agent_grant := global ext::napalm::ClientTokenAgentGrant;   abstract type NapalmTextEmbedding3Small extending ext::ai::EmbeddingModel {    annotation ext::ai::model_name := 'openai/text-embedding-3-small';    annotation ext::ai::model_provider := 'napalm';    annotation ext::ai::embedding_model_max_input_tokens := '8191';    annotation ext::ai::embedding_model_max_batch_tokens := '8191';    annotation ext::ai::embedding_model_max_output_dimensions := '1536';    annotation ext::ai::embedding_model_supports_shortening := 'true';  }   type Article {    required owner: ext::auth::Identity;    required title: str;    required body: str;    required is_archived: bool {      default := false;    };     deferred index ext::ai::index(embedding_model := 'openai/text-embedding-3-small')      on (.title ++ ' ' ++ .body);    index fts::index on ((      fts::with_options(.title, language := fts::Language.eng, weight_category := fts::Weight.A),      fts::with_options(.body, language := fts::Language.eng, weight_category := fts::Weight.B)    ));     access policy owner_has_full_access      allow all      using (.owner ?= global caller);    access policy read_only_agent_cannot_write      deny insert, update, delete      using ((global agent_grant).is_read_only ?= true);  }}

Search under caller policies#

Semantic vector search catches paraphrases while lexical search catches exact identifiers. POST /search runs both over one indexed type and fuses the rankings with reciprocal rank fusion. Access policies run inside the scan, so every returned match belongs to rows the caller may read. The assistant route invokes hybrid search through napalm.search('Article', message).

POST /search requires an endpoint passthrough mode that admits the caller. When user sessions are restricted to deployed queries, expose hybrid search through a deployed query instead.

dbschema/queries/findArticles.edgeql
with hits := (  select ext::ai::hybrid_search(Article, <str>$prompt, language := 'eng')  filter not .object.is_archived  order by .score desc  limit 6)select hits.object { id, title, body }

Full-text search matches newly committed rows immediately, while semantic search includes new rows as soon as background embedding completes. For typeahead inputs, deploy a lexical full-text query with custom filters.

dbschema/queries/suggestArticles.edgeql
with hits := (  select fts::search(Article, <str>$prompt, language := 'eng')  filter not .object.is_archived  order by .score desc  limit 6)select hits.object { id, title }

Answer questions and propose changes#

POST /ask takes a question in plain language and drafts one EdgeQL query from your schema. Because EdgeQL is decidable before execution, Napalm proves that the query compiles and performs zero writes before running a read under the caller’s policies, returning a written answer alongside the source rows.

A question that requires a mutation executes nothing on live data. Instead, the response returns proposed with the drafted statement and reason. With isDryRun: true, Napalm executes that statement inside a rolled-back transaction as the user and reports every record the statement would have changed.

app/api/assistant/route.ts
// app/api/assistant/route.tsimport { NapalmClient } from 'napalm-client' export async function POST(request: Request) {  const session = request.headers.get('Authorization')?.replace(/^Bearer\s+/i, '')  if (!session) return new Response('Sign in first.', { status: 401 })   const { message } = (await request.json()) as { message: string }  // Forward the signed-in user's session so every query enforces their access rules.  const napalm = new NapalmClient('https://notes.napalmdata.com', { token: session })   // Hybrid vector and full-text search returns only rows this user can read.  const sources = await napalm.search<{ title: string; body: string }>('Article', message, {    limit: 6,    fields: ['title', 'body'],  })   const asked = await napalm.ask(message, { isDryRun: true })   if (asked.proposed) {    // Return the rolled-back diff so the user can review and approve the change.    return Response.json({      kind: 'proposal',      query: asked.proposed.query,      reason: asked.proposed.reason,      changes: asked.proposed.dry_run?.changes ?? [],      failure: asked.proposed.dry_run_failure ?? null,    })  }   return Response.json({ kind: 'answer', answer: asked.answer, rows: asked.data, sources })}

Preview and approve writes#

proposed.dry_run.changes lists each affected record’s values before and after, and nothing commits until the user approves. If an access rule would refuse the mutation, the dry run surfaces that refusal in proposed.dry_run_failure so broken proposals are never offered.

Rolled-back mutation previews

Dry runs execute inside a rolled-back transaction and return row diffs.

Render the affected records in a confirmation card whose button posts the drafted statement to POST /query under the user’s own session, where your schema policies verify the write once more at commit:

components/ProposalCard.tsx
// components/ProposalCard.tsx'use client' import { useState } from 'react'import type { ProposedChange } from 'napalm-client'import { useNapalm } from 'napalm-client/react' export function ProposalCard({ query, changes }: { query: string; changes: readonly ProposedChange[] }) {  const napalm = useNapalm()  const [status, setStatus] = useState<'idle' | 'applying' | 'applied' | 'refused'>('idle')   async function approve() {    setStatus('applying')    const made = await napalm.fetch('https://notes.napalmdata.com/query', {      method: 'POST',      headers: { 'Content-Type': 'application/json' },      body: JSON.stringify({ query }),    })    setStatus(made.ok ? 'applied' : 'refused')  }   return (    <section aria-label="Proposed changes">      <p>{changes.length} records would change:</p>      <ul>        {changes.map((change) => (          <li key={change.id}>            {change.action} {change.type}          </li>        ))}      </ul>      <button type="button" disabled={status !== 'idle'} onClick={approve}>        {status === 'applied' ? 'Done' : status === 'refused' ? 'Refused' : 'Make these changes'}      </button>    </section>  )}

Stream a summary#

POST /ask returns its answer in one piece after the model finishes, while a summary reads better as tokens arrive. A streamed action runs its gatekeeper query as the signed-in user first so the model summarizes only articles that user may read:

dbschema/queries/summarizeArticle.edgeql
# Load the article under the caller's select policy before calling the model.select Article { title, body }filter .id = <uuid>$article

Write the handler as an async function* so each yielded text delta becomes one SSE frame. Install @anthropic-ai/sdk in your project, stage ANTHROPIC_API_KEY with napalm handlers secrets set and deploy with napalm handlers deploy notes:

handlers/summarizeArticle.ts
import Anthropic from '@anthropic-ai/sdk'import type { HandlerContext } from 'napalm-client' const claude = new Anthropic() export async function* summarizeArticle(call: HandlerContext<{ title: string; body: string }>) {  const [article] = call.rows  const reply = claude.beta.messages.stream({    model: 'claude-opus-5-5',    max_tokens: 64000,    // Route declined requests to a default fallback model.    betas: ['server-side-fallback-2026-07-01'],    fallbacks: 'default',    messages: [      {        role: 'user',        content: `Summarize this article in three sentences.\n\n${article.title}\n\n${article.body ?? ''}`,      },    ],  })  // Yield each text delta as an SSE frame.  for await (const event of reply) {    if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') yield event.delta.text  }}

Subscribe from React with useStreamedAction, which invokes the action under the user’s session, appends each frame as it arrives and cancels the in-flight stream on Stop:

components/Summary.tsx
// components/Summary.tsx'use client' import { useStreamedAction } from 'napalm-client/react' export function Summary({ article }: { article: string }) {  const summary = useStreamedAction<{ article: string }>('summarizeArticle')   return (    <section aria-label="Summary">      {summary.isStreaming ? (        <button type="button" onClick={summary.stop}>          Stop        </button>      ) : (        <button type="button" onClick={() => summary.call({ article })}>          Summarize        </button>      )}      <p>{summary.text}</p>      {summary.error && <p role="alert">{summary.error.message}</p>}    </section>  )}

Asking to summarize another user’s article fails with 403 nothing_found before the handler ever runs.

Connect external MCP assistants#

The same rules hold for an outside assistant connected to your project’s MCP server. The assistant acts as the approving user within the access granted at consent.

  1. Configure your consent page

    Set agentConsentUrl in your project’s API settings. When a user connects an MCP client to https://notes.napalmdata.com/mcp, Napalm redirects their browser to that URL with a signed request token.

  2. Render the approval prompt

    Display the requesting client name and let the user choose an expiration window alongside read-only or read-write access.

    app/consent/agent/page.tsx
    // app/consent/agent/page.tsxasync function allow(request: string, session: string, isReadOnly: boolean) {  // Decode the request payload to display client details (Napalm verifies the signature on POST).  const asked = JSON.parse(atob(request.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')))  // asked.client_name, asked.redirect_uri, asked.asked ('read', 'write' or 'unsaid')   const answer = await fetch('https://notes.napalmdata.com/sign-in/agents/allow', {    method: 'POST',    headers: { Authorization: `Bearer ${session}`, 'Content-Type': 'application/json' },    body: JSON.stringify({ request, isReadOnly, days: 30 }),  })  location.href = (await answer.json()).redirectTo}
  3. Enforce read-only grants in the schema

    Napalm blocks writes from a read-only grant before execution, and read_only_agent_cannot_write in the schema above enforces the same check inside the database. Add deny policies checking global ext::napalm::ClientTokenAgentGrant to hide sensitive types from external assistants even when the approving user can read those rows.

Each approved connection creates an ext::napalm::AgentGrant row owned by that user. Deleting the row revokes the assistant’s access on the next request. See Sign-in.

Scope background agents with grants#

When a background agent works unattended without a live user session, assign the agent its own sign-in identity so it starts with access to zero rows.

Expiring record grants

Grant rows expose chosen records to an agent identity until expiry.

Model that boundary as an AgentGrant type linking the owner, the agent’s identity, the permitted Note records and an expires timestamp:

dbschema/default.gel
using extension auth;using extension napalm;using future simple_scoping; module default {  global caller := global ext::auth::ClientTokenIdentity;   # Client queries cannot reference ext::auth types directly, so this helper resolves an Identity by UUID.  function identity_by_id(target: uuid) -> optional ext::auth::Identity    using (select ext::auth::Identity filter .id = target);   type Person {    required identity: ext::auth::Identity {      constraint exclusive;    };    required name: str;     access policy self_has_full_access      allow all      using (.identity ?= global caller);  }   type AgentGrant {    required person: Person;    required agent: ext::auth::Identity;    multi notes: Note;    required expires: datetime;     access policy person_has_full_access      allow all      using (.person.identity ?= global caller);    access policy agent_can_see_its_own      allow select      using (.agent ?= global caller);  }   type Note {    required title: str;    required author: Person;     access policy author_has_full_access      allow all      using (.author.identity ?= global caller);    access policy granted_agent_can_read      allow select      using (exists (        select .<notes[is AgentGrant]        filter .agent ?= global caller          and .expires > datetime_of_statement()      ));  }}

That schema gives each grant three database-enforced properties:

Linked records only
The agent reads only notes linked on its grant. Adversarial text inside a note cannot widen access because the compiled policy enforces the boundary.
Statement-clock expiry
The policy compares expires against datetime_of_statement() on every query, so grants expire automatically without a background cleanup job.
Instant revocation
Deleting the grant cuts off the agent’s next query immediately. See Agent access & grants.

Check the assistant#

Your terminal
# 1. Hybrid search as a signed-in user returns only permitted articles.curl https://notes.napalmdata.com/search \  -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \  -d '{ "type": "Article", "query": "renewal dates", "limit": 6, "fields": ["title"] }' # 2. Ask a read-only question under the user's session.curl https://notes.napalmdata.com/ask \  -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \  -d '{ "question": "Which of my articles mention renewals?" }' # 3. Preview a mutating request as a rolled-back dry run.curl https://notes.napalmdata.com/ask \  -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \  -d '{ "question": "Archive my articles about renewals", "is_dry_run": true }'

The first request returns only articles owned by the signed-in user. The second returns a natural-language answer alongside the source rows read. The third returns a proposed payload with rolled-back row diffs while leaving live articles untouched, which you can confirm by re-running the first request.

Type a word or two to search every docs page.