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
- —
- In the schema
ext::napalm::AgentGrant
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 person may read.
- Answers
- A natural-language question compiles into one type-checked query that executes read-only as that person.
- Proposals
- Proposed mutations return record-by-record diffs, and nothing commits until the person approves.
- Outside assistants
- External assistants connected over OAuth follow the same rules, with optional read-only enforcement.
Before you start#
- Search indexes
- An
ext::ai::indexand anfts::indexon 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
- A query written from your schema answers each question, so the project must share the schema. Run
napalm endpoint notes --share-schema. - Passthrough for sessions
- POST /ask answers a signed-in person only while the project’s passthrough is
all. Withkeys, people can still search through deployed queries and cannot ask ad-hoc questions.
Run the assistant as the person#
Conventional copilots hold a backend key that can read every customer’s rows, relying on system prompts and hand-written WHERE filters to stay in bounds. One missed filter leaks another tenant’s data.
Here the assistant holds no service key and calls your project with the bearer session of the signed-in person. Searches, POST /ask queries and approved writes enforce the same access rules as the user’s own clicks, so no prompt can widen the rows that session can read.
Caller-session copilot with human sign-off
The assistant searches via POST /search and drafts via POST /ask wearing the user’s session, holding mutating statements at a confirmation gate until explicit user approval.
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 as the person#
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 this via napalm.search('Article', message).
The search route needs a caller the passthrough admits. If a project holds people to deployed queries, deploy the search as your own query with any filters you need.
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 }Search by words finds a new row at once, and search by meaning finds the row after background embedding finishes. You can deploy a words-only search as a statement with your own filters. Use a words-only search for a field that completes as the person types.
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 person and reports every record the statement would have changed.
// 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 } // The person's own session: every read and write below is theirs. const napalm = new NapalmClient('https://notes.napalmdata.com', { token: session }) // By meaning and by words together. A row this person can't read is never a match. 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) { // Nothing was changed. Hand back what would change, for the person to approve. 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 a change#
proposed.dry_run.changes lists each affected record’s values before and after. Nothing commits until the person approves. Approving sends the proposed statement to POST /query with the person’s own session so your schema policies verify the write once more at commit.
Rolled-back before-and-after diff via is_dry_run
is_dry_run: true runs the drafted mutation inside a rolled-back SQL transaction under the user’s session, populating proposed.dry_run.changes or proposed.dry_run_failure when a policy refuses.
// 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> )}If an access rule would refuse the mutation, the dry run surfaces the refusal in proposed.dry_run_failure so nothing broken is offered for approval.
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, then streams each text delta to the browser.
# The person's article, for the model to summarize. Another person's article finds nothing.select Article { title, body }filter .id = <uuid>$articleimport 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, // A fallback model answers a request Claude Opus 5.5 declines. 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 ?? ''}`, }, ], }) // One frame for each piece of text, sent as the model writes it. for await (const event of reply) { if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') yield event.delta.text }}Write the handler as an async function* so each yielded text chunk 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.
// 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> )}useStreamedAction invokes the action under the user’s session and appends each frame as it arrives, while Stop cancels the in-flight stream. Asking to summarize another user’s article fails with 403 nothing_found before the handler ever runs.
Let Claude or ChatGPT in#
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.
Name your consent page
Set
agentConsentUrlin the project’s API settings to a page in your app. When someone connects an assistant tohttps:/, Napalm sends the person’s browser to that page with a/ notes.napalmdata.com/ mcp request.Let the person choose
Show the requesting assistant, and let the user pick a duration and either read-only or read-write access.
app/consent/agent/page.tsx// app/consent/agent/page.tsx: the page your agentConsentUrl namesasync function allow(request: string, session: string, isReadOnly: boolean) { // Who is asking, to show the person: the first part of the request, which Napalm checks again on the 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}Hold a read-only grant in the schema too
Napalm blocks writes from a read-only grant before execution, and
read_only_agent_cannot_writein the schema above enforces the same check inside the database. Adddenyrules onglobal ext::napalm::ClientTokenAgentGrantto hide sensitive types from external assistants even when the approving user can read them.
Each connection is a row the person can read and delete. Deleting the row ends the assistant’s access at the next call. Sign-in covers the whole exchange.
Give a background agent a few records#
An unattended background agent gets its own sign-in identity and reads only the records linked on a grant row until the expiration time set by the owner.
Row-and-time-scoped background grants
A grant record binds an agent’s Identity to chosen records until expires, evaluated against datetime_of_statement() on every query and revocable in one delete.
using extension auth;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; # A statement sent to the API can't name ext::auth's types, so the schema looks an identity up for it. 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() )); }}- Handed-over records only
- The agent can read only the notes linked on its grant. Adversarial text inside a note cannot widen access because the compiled policy enforces the boundary rather than the prompt.
- Ends on time
- The rule compares
expiresagainstdatetime_of_statement()on every call. Nothing has to run in the background for the grant to lapse. - Revoked by a delete
- Delete the grant and the agent’s next statement finds nothing. See Agent access & grants.
Check the assistant#
# 1. Search as a signed-in person: only their articles come back.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. A question that reads.curl https://notes.napalmdata.com/ask \ -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \ -d '{ "question": "Which of my articles mention renewals?" }' # 3. A question that would change something: proposed, shown, and not made.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 call answers articles, and every article is the signed-in person’s. The second answers in words with the rows read. The third answers proposed with the planned changes, and the articles stay unchanged. Run the first call again to confirm.