create-agent-with-sanity-context

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Build an Agent with Sanity Context

借助Sanity Context构建Agent

Give AI agents intelligent access to your Sanity content. Unlike embedding-only approaches, Sanity Context is schema-aware—agents can reason over your content structure, query with real field values, follow references, and combine structural filters with semantic search.
What this enables:
  • Agents understand the relationships between your content types
  • Queries use actual schema fields, not just text similarity
  • Results respect your content model (categories, tags, references)
  • Semantic search is available when needed, layered on structure
Sanity Context gives agents your schema and teaches them GROQ, but it can't know your domain. You close that gap through the Instructions field (dataset-specific query guidance) and optionally the system prompt (agent behavior and tone).
Three actors in this workflow:
  • You — the agent executing this skill, helping the user set things up
  • The user — the human you're working with, who knows their domain and data
  • The production agent — the agent being built, which will serve end users
让AI Agent能够智能访问你的Sanity内容。与仅依赖嵌入的方案不同,Sanity Context具备 schema 感知能力——Agent可以理解你的内容结构、使用真实字段值进行查询、追踪关联关系,并将结构筛选与语义搜索相结合。
实现的功能:
  • Agent理解内容类型之间的关联关系
  • 查询使用实际的schema字段,而非仅依赖文本相似度
  • 结果遵循你的内容模型(分类、标签、关联关系)
  • 按需启用语义搜索,基于内容结构进行分层
Sanity Context会向Agent提供你的schema并教授GROQ语法,但它无法了解你的业务领域。你可以通过Instructions字段(数据集专属的查询指引)和可选的系统提示词(Agent的行为与语气)来弥补这一差距。
此流程中的三个角色:
  • —— 执行此技能的Agent,帮助用户完成搭建工作
  • 用户 —— 与你协作的开发者,熟悉自身业务领域与数据
  • 生产环境Agent —— 正在构建的Agent,将为终端用户提供服务

What You'll Need

准备工作

Before starting, gather these credentials:
CredentialWhere to get it
Sanity Project IDYour
sanity.config.ts
or sanity.io/manage
Dataset nameUsually
production
— check your
sanity.config.ts
Sanity API read tokenRun
npx sanity tokens add "Sanity Context" --role=viewer --yes --json
from the project directory (or pass
--project-id=<id>
). Alternatively, create at sanity.io/manage → Project → API → Tokens with Viewer role.
LLM API keyFrom your LLM provider (Anthropic, OpenAI, etc.) — any provider works
开始前,请准备以下凭证:
凭证名称获取方式
Sanity Project ID
sanity.config.ts
中查看,或访问sanity.io/manage
数据集名称通常为
production
——可在
sanity.config.ts
中确认
Sanity API 只读令牌在项目目录中运行
npx sanity tokens add "Sanity Context" --role=viewer --yes --json
(或添加
--project-id=<id>
参数)。也可在sanity.io/manage → 项目 → API → 令牌页面创建Viewer权限的令牌。
LLM API密钥从你的LLM供应商获取(Anthropic、OpenAI等)——支持任意供应商

How Sanity Context Works

Sanity Context工作原理

The Sanity Context MCP server gives AI agents structured access to Sanity content. The core integration pattern:
  1. Initial Context: Fetch schema context via the
    /initial-context
    HTTP endpoint and inject it into the system prompt
  2. MCP Connection: HTTP transport to the Sanity Context URL
  3. Authentication: Bearer token using Sanity API read token
  4. Tool Discovery: Get available tools from MCP client, pass to LLM
  5. System Prompt: Tell the production agent its role, tone, and boundaries
MCP URL formats:
  • https://api.sanity.io/v2026-03-03/context/mcp/:projectId/:dataset
    Base URL. No document needed, configure via query params or use as-is.
  • https://api.sanity.io/v2026-03-03/context/mcp/:projectId/:dataset/:slug
    Document URL. Applies the configuration from a Sanity Context document.
Sanity Context documents (type
sanity.agentContext
) are created in Sanity Studio and configure the MCP endpoint. They have three fields:
FieldSchema fieldPurpose
Slug
slug
Unique URL identifier — becomes the
:slug
in the MCP URL
Instructions
instructions
Domain-specific guidance for the agent, injected into tool descriptions
Content Filter
groqFilter
A GROQ expression scoping which documents the agent can access
This means Studio users can manage agent behavior without touching code — updating instructions or narrowing the content filter takes effect immediately.
URL query params override the document's configuration (useful for testing and development):
  • ?instructions=<content>
    — Override instructions (use
    ?instructions=""
    for a blank slate)
  • ?groqFilter=<expression>
    — Override the content filter
The integration is simple: Connect to the MCP URL, get tools, use them. The reference implementation shows one way to do this—adapt to your stack and LLM provider.
Initial context (recommended):
Always fetch the schema context via the
/initial-context
HTTP endpoint and inject it into the system prompt. This gives a significant latency improvement on the first message—the agent already knows the schema and available tools without needing a tool call. It also enables better prompt caching since the schema prefix is stable across conversations.
Append
/initial-context
to the MCP URL path (before any query params), using the same auth header:
bash
curl https://api.sanity.io/v2026-03-03/context/mcp/:projectId/:dataset/:slug/initial-context \
  -H "Authorization: Bearer $SANITY_API_READ_TOKEN"
Fetch once, cache the result, and include it in your system prompt. When using this, exclude the
initial_context
tool from the tools passed to the LLM to avoid redundant calls.
If you don't control the system prompt (e.g. using a third-party MCP client), the
initial_context
MCP tool still works — the agent will call it on the first message instead.
Sanity Context MCP服务器为AI Agent提供Sanity内容的结构化访问能力。核心集成模式:
  1. 初始上下文:通过
    /initial-context
    HTTP端点获取schema上下文并注入系统提示词
  2. MCP连接:通过HTTP协议连接到Sanity Context URL
  3. 身份验证:使用Sanity API只读令牌作为Bearer令牌
  4. 工具发现:从MCP客户端获取可用工具并传递给LLM
  5. 系统提示词:定义生产环境Agent的角色、语气与边界
MCP URL格式:
  • https://api.sanity.io/v2026-03-03/context/mcp/:projectId/:dataset
    —— 基础URL。无需配置文档,可通过查询参数配置或直接使用。
  • https://api.sanity.io/v2026-03-03/context/mcp/:projectId/:dataset/:slug
    —— 文档URL。应用Sanity Context文档中的配置。
Sanity Context文档(类型为
sanity.agentContext
)在Sanity Studio中创建,用于配置MCP端点。包含三个字段:
字段Schema字段用途
Slug
slug
唯一URL标识——对应MCP URL中的
:slug
部分
Instructions
instructions
为Agent提供业务领域专属指引,注入到工具描述中
内容筛选器
groqFilter
GROQ表达式,限定Agent可访问的文档范围
这意味着Studio用户无需修改代码即可管理Agent行为——更新指引或缩小内容筛选范围会立即生效。
URL查询参数可覆盖文档配置(适用于测试与开发):
  • ?instructions=<content>
    —— 覆盖指引内容(使用
    ?instructions=""
    可清空指引)
  • ?groqFilter=<expression>
    —— 覆盖内容筛选器
集成流程简单:连接到MCP URL,获取工具并使用即可。参考实现展示了一种集成方式——可根据你的技术栈与LLM供应商进行适配。
推荐使用初始上下文:
始终通过
/initial-context
HTTP端点获取schema上下文并注入系统提示词。这能显著提升第一条消息的响应速度——Agent无需调用工具即可提前了解schema与可用工具。同时,由于schema前缀在对话中保持稳定,还能优化提示词缓存效果。
在MCP URL路径后添加
/initial-context
(在查询参数之前),使用相同的授权头:
bash
curl https://api.sanity.io/v2026-03-03/context/mcp/:projectId/:dataset/:slug/initial-context \
  -H "Authorization: Bearer $SANITY_API_READ_TOKEN"
获取一次后缓存结果,并将其包含在系统提示词中。使用此方式时,需将
initial_context
工具从传递给LLM的工具列表中排除,避免重复调用。
如果你无法控制系统提示词(例如使用第三方MCP客户端),
initial_context
MCP工具仍可正常工作——Agent会在第一条消息时调用该工具。

Available MCP Tools

可用MCP工具

ToolPurpose
initial_context
Get compressed schema overview (types, fields, document counts). Also available via the
/initial-context
HTTP endpoint.
groq_query
Execute GROQ queries with optional semantic search
schema_explorer
Get detailed schema for a specific document type
For development and debugging: The general Sanity MCP provides broader access to your Sanity project (schema deployment, document management, etc.). Useful during development but not intended for customer-facing applications.
工具名称用途
initial_context
获取压缩后的schema概览(类型、字段、文档数量)。也可通过
/initial-context
HTTP端点获取。
groq_query
执行GROQ查询,支持可选的语义搜索
schema_explorer
获取特定文档类型的详细schema信息
开发与调试专用:通用Sanity MCP提供对Sanity项目的更广泛访问权限(schema部署、文档管理等)。适用于开发阶段,但不建议用于面向客户的应用。

Before You Start: Understand the User's Situation

开始前:了解用户场景

A complete integration has four distinct components that may live in different places:
ComponentWhat it isExamples
1. Studio SetupConfigure the context plugin and create Sanity Context documentsSanity Studio (separate repo or embedded)
2. Agent ImplementationCode that connects to Sanity Context and handles LLM interactionsNext.js API route, Express server, Python service, or any MCP-compatible client
3. FrontendUI for users to interact with the agentChat widget, search interface, CLI—or none for backend services
4. FunctionsScheduled classification via Sanity Blueprints
sanity.blueprint.ts
+
functions/
directory — has its own placement constraints (see Sanity Blueprints & Functions)
A deployed Studio (v5.1.0+) is always required. Not every integration needs the Sanity Context plugin or document—the base MCP URL works without them, so users can start with just agent implementation and add document configuration later—or vice versa. Frontend depends on the use case (many agents run as backend services or integrate into existing UIs).
Before writing any code, inspect the project to understand:
  1. Project layout: Read the top-level
    package.json
    (check for
    workspaces
    or a
    pnpm-workspace.yaml
    ), locate the lockfile, and map out the distinct apps/packages. This determines where
    sanity.blueprint.ts
    and
    functions/
    will go — see Sanity Blueprints & Functions.
  2. Their stack: What framework/runtime? (Next.js, Remix, Node server, Python, etc.)
  3. Their AI library: Vercel AI SDK, LangChain, direct API calls, etc.
  4. Their domain: What will the agent help with? (Shopping, docs, support, search, etc.)
  5. Which components they need help with: They may only need one or two.
  • Components in different repos (most common): You may only have access to one component. Complete what you can, then tell the user what steps remain for the other repos.
  • Co-located components: All in the same project—work through them based on what the user wants to tackle first.
  • No Studio in the codebase? Ask the user if Studio setup is done elsewhere, or if they want to skip the Sanity Context plugin and document for now—the base URL works without them.
The reference patterns use Next.js + Vercel AI SDK, but adapt to whatever the user is working with.
完整的集成包含四个独立组件,可能部署在不同位置:
组件说明示例
1. Studio配置配置上下文插件并创建Sanity Context文档Sanity Studio(独立仓库或嵌入式)
2. Agent实现连接Sanity Context并处理LLM交互的代码Next.js API路由、Express服务器、Python服务或任何兼容MCP的客户端
3.前端用户与Agent交互的UI聊天组件、搜索界面、CLI——后端服务可无需前端
4.函数通过Sanity Blueprints执行定时分类
sanity.blueprint.ts
+
functions/
目录——有特定的部署约束(详见Sanity Blueprints & Functions)
始终需要部署Studio(v5.1.0+)。并非所有集成都需要Sanity Context插件或文档——基础MCP URL可直接使用,用户可先实现Agent,后续再添加文档配置,反之亦然。前端是否需要取决于使用场景(许多Agent作为后端服务运行或集成到现有UI中)。
编写代码前,请先分析项目:
  1. 项目结构:查看顶层
    package.json
    (检查是否包含
    workspaces
    pnpm-workspace.yaml
    ),找到锁文件,梳理不同的应用/包。这将决定
    sanity.blueprint.ts
    functions/
    的位置——详见Sanity Blueprints & Functions
  2. 技术栈:使用的框架/运行时?(Next.js、Remix、Node服务器、Python等)
  3. AI库:Vercel AI SDK、LangChain、直接API调用等
  4. 业务领域:Agent将用于什么场景?(电商、文档、客服、搜索等)
  5. 需要帮助的组件:用户可能只需要其中一两个组件的帮助
  • 组件位于不同仓库(最常见):你可能只能访问其中一个组件。完成力所能及的部分后,告知用户其他仓库需要完成的步骤。
  • 组件共存于同一项目:所有组件都在同一个项目中——根据用户需求优先处理对应组件。
  • **代码库中无Studio?**询问用户是否已在其他位置完成Studio配置,或是否想暂时跳过Sanity Context插件与文档——基础URL可直接使用。
参考模式使用Next.js + Vercel AI SDK,但可适配用户使用的任何技术栈。

Workflow

工作流程

Always present the full workflow. Even if the user's request seems narrow, inform them of all four steps — you don't have to implement everything, but they should know what's available. A working chatbot without Insights is only half the value. Walk the user through all four steps, explaining what each unlocks:
  1. Build the Agent — Get a working chatbot connected to their content
  2. Studio Setup — Configure the plugin and create a Sanity Context document
  3. Conversation Insights — Track and classify conversations (this is what makes the data useful)
  4. Tune the Agent — Refine instructions and system prompt using the tuning skills
After completing each step, proactively present the next one. Only stop when all steps are done or the user explicitly defers.
请始终展示完整工作流程。即使用户的需求看似单一,也要告知所有四个步骤——你无需实现所有内容,但用户需要了解可用选项。没有Insights的聊天机器人只能发挥一半价值。引导用户完成所有步骤,解释每个步骤的作用:
  1. 构建Agent —— 搭建可连接到内容的可用聊天机器人
  2. 配置Studio —— 配置插件并创建Sanity Context文档
  3. 对话Insights —— 追踪并分类对话(这是让数据产生价值的关键)
  4. 优化Agent —— 使用调优技能优化指引与系统提示词
完成每个步骤后,主动展示下一个步骤。仅在所有步骤完成或用户明确推迟时停止。

Quick Validation (Optional)

快速验证(可选)

Before building the production agent, validate that the MCP endpoint is reachable. If the user doesn't have a read token yet, offer to create one from the terminal — detect the
projectId
from
sanity.config.ts
or
sanity.cli.ts
if available:
bash
npx sanity tokens add "Sanity Context" --role=viewer --yes --json
This outputs JSON with the token value. If not inside a Sanity project directory, pass
--project-id=<id>
explicitly.
Then test the endpoint:
bash
curl -X POST https://api.sanity.io/v2026-03-03/context/mcp/:projectId/:dataset \
  -H "Authorization: Bearer $SANITY_API_READ_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'
This confirms the token works and the endpoint is reachable. The base URL (no slug) works without a Sanity Context document—add a slug to apply a document's configuration.
构建生产环境Agent前,验证MCP端点是否可达。如果用户还没有只读令牌,可提供终端创建命令——如果可用,从
sanity.config.ts
sanity.cli.ts
中自动检测
projectId
bash
npx sanity tokens add "Sanity Context" --role=viewer --yes --json
此命令会输出包含令牌值的JSON。如果不在Sanity项目目录中,需显式添加
--project-id=<id>
参数。
然后测试端点:
bash
curl -X POST https://api.sanity.io/v2026-03-03/context/mcp/:projectId/:dataset \
  -H "Authorization: Bearer $SANITY_API_READ_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'
此命令可验证令牌是否有效以及端点是否可达。基础URL(无slug)无需Sanity Context文档即可工作——添加slug可应用文档配置。

Step 1: Build the Agent (Adapt to user's stack)

步骤1:构建Agent(适配用户技术栈)

The user already has an agent or MCP client? They just need to connect it to their Sanity Context URL with a Bearer token. The tools will appear automatically.
Building from scratch? Help the user set up the MCP connection and LLM integration. The reference implementations use Vercel AI SDK with Anthropic, but the pattern works with any LLM provider (OpenAI, local models, etc.). Start with the basics and add advanced patterns as needed.
Framework-specific guides:
  • Next.js: See references/nextjs-agent.md
  • SvelteKit: See references/sveltekit-agent.md
  • Other stacks (Express, Remix, Python, LangChain): See references/adapting-to-stacks.md
System prompts (applies to all frameworks): See references/system-prompts.md for structure and domain-specific examples (e-commerce, docs, support, content curation).
The framework guides cover:
  • Core setup (required): MCP connection, authentication, basic chat route
  • Frontend (optional): Chat component for the framework, including markdown rendering (LLM responses are markdown — a renderer like
    react-markdown
    or
    marked
    is needed to display formatted output)
  • Advanced patterns (optional): Client-side tools, auto-continuation, custom directive rendering
**用户已有Agent或MCP客户端?**只需将其连接到Sanity Context URL并使用Bearer令牌即可,工具会自动显示。
**从零开始构建?**帮助用户配置MCP连接与LLM集成。参考实现使用Vercel AI SDK与Anthropic,但该模式适用于任何LLM供应商(OpenAI、本地模型等)。先实现基础功能,再按需添加高级模式。
框架专属指南:
  • Next.js:查看references/nextjs-agent.md
  • SvelteKit:查看references/sveltekit-agent.md
  • 其他技术栈(Express、Remix、Python、LangChain):查看references/adapting-to-stacks.md
系统提示词(适用于所有框架):查看references/system-prompts.md获取结构与领域专属示例(电商、文档、客服、内容策划)。
框架指南包含:
  • 核心配置(必需):MCP连接、身份验证、基础聊天路由
  • 前端(可选):框架专属聊天组件,包含markdown渲染(LLM响应为markdown格式——需要
    react-markdown
    marked
    等渲染器来显示格式化输出)
  • 高级模式(可选):客户端工具、自动续聊、自定义指令渲染

Step 2: Set up Sanity Studio

步骤2:配置Sanity Studio

Help the user configure the
@sanity/context/studio
plugin in their Studio and create a Sanity Context document. This document controls what the production agent can see (via
groqFilter
) and what guidance it receives (via
instructions
).
See references/studio-setup.md
帮助用户在Studio中配置
@sanity/context/studio
插件并创建Sanity Context文档。该文档控制生产环境Agent的可见内容(通过
groqFilter
)与获取的指引(通过
instructions
)。
查看references/studio-setup.md

Step 3: Conversation Insights (Recommended)

步骤3:对话Insights(推荐)

Recommend the user sets up Insights. Without tracking, there's no way to know if the agent is actually helping users or failing silently. Insights shows you what users ask, where the agent struggles, and what content is missing — data you need to improve the agent over time.
What this unlocks:
  • See which conversations succeed and which fail
  • Discover content gaps — topics users ask about that the agent can't answer well
  • Debug specific conversations with full transcripts
  • Compare performance across multiple agents
Setup is two parts — do both:
  1. Telemetry — Add one integration to your existing
    streamText
    call (saves conversations)
  2. Classification — Deploy a scheduled function that analyzes conversations with AI
Telemetry without classification just stores raw conversations. Classification is what extracts success scores, sentiment, and content gaps — the actual insights. Always set up both.
Follow references/conversation-classification.md to set this up. The guide covers both parts end-to-end. The dashboard appears in Studio automatically once deployed.
建议用户配置Insights。没有追踪功能,无法了解Agent是否真正帮助用户或出现静默故障。Insights可展示用户的问题、Agent的薄弱环节以及缺失的内容——这些数据是持续优化Agent的关键。
实现的价值:
  • 查看对话的成功与失败情况
  • 发现内容缺口——用户询问但Agent无法很好回答的话题
  • 通过完整对话记录调试特定问题
  • 对比多个Agent的性能
配置分为两部分——需全部完成:
  1. 遥测 —— 在现有
    streamText
    调用中添加集成(保存对话记录)
  2. 分类 —— 部署定时函数,使用AI分析对话
仅配置遥测只会存储原始对话记录。分类功能才会提取成功评分、情感倾向与内容缺口——这才是真正的Insights。请务必同时配置两者。
按照references/conversation-classification.md完成配置。该指南涵盖从开始到结束的所有步骤。部署完成后,仪表盘会自动在Studio中显示。

Step 4: Tune Your Agent (Recommended)

步骤4:优化Agent(推荐)

Once the production agent works:
  1. Tune the Instructions field using the
    dial-your-context
    skill — an interactive session where you explore the user's dataset together, verify findings, and produce concise Instructions that teach the production agent what the schema alone doesn't make obvious: counter-intuitive field names, second-order reference chains, data quality issues, required filters, and query patterns. The skill can also help configure a
    groqFilter
    to scope what content the production agent sees.
  2. Shape the system prompt (optional) using the
    shape-your-agent
    skill — if the user controls the production agent's system prompt, this helps define tone, boundaries, and guardrails. Skip this if the user doesn't control the system prompt.
生产环境Agent可用后:
  1. 优化Instructions字段:使用
    dial-your-context
    技能——通过交互式会话与用户一起探索数据集、验证结果,并生成简洁的Instructions,向生产环境Agent传授schema无法体现的信息:非直观字段名称、二级关联链、数据质量问题、必需筛选器与查询模式。该技能还可帮助配置
    groqFilter
    以限定生产环境Agent的内容访问范围。
  2. 优化系统提示词(可选):使用
    shape-your-agent
    技能——如果用户可控制生产环境Agent的系统提示词,此技能可帮助定义语气、边界与防护规则。如果用户无法控制系统提示词,可跳过此步骤。

Sanity Blueprints & Functions

Sanity Blueprints & Functions

Scheduled classification uses Sanity Blueprints to deploy Sanity Functions.
定时分类使用Sanity Blueprints部署Sanity Functions

Placement principles

部署原则

Before adding files, search the project for an existing
sanity.blueprint.ts
. If one exists with deployed functions, add the new function there — even if it's not next to the lockfile. An existing working setup takes precedence over the default placement rules below. Only follow these rules when creating a new blueprint from scratch.
Find the project's lockfile (
yarn.lock
,
pnpm-lock.yaml
, or
package-lock.json
). Two rules for new blueprints:
  1. sanity.blueprint.ts
    must be in the same directory as the lockfile.
    The CLI detects the package manager from the lockfile. If no lockfile is present, pass
    --fn-installer pnpm
    (or
    npm
    /
    yarn
    ) to the deploy command.
  2. Function
    src
    paths are resolved relative to the blueprint file.
    By default a function named
    classify-conversations
    maps to
    functions/classify-conversations/
    next to the blueprint. Use the
    src
    property in
    defineScheduledFunction
    to point to a different directory.
In a monorepo with no existing blueprint, the lockfile is at the workspace root — so
sanity.blueprint.ts
and
functions/
go there too, alongside the root
package.json
. However, if a blueprint already exists in a subdirectory (e.g.
apps/studio/
) and functions are successfully deploying from there, use that location. The CLI can work from subdirectories when configured correctly (e.g. with
--fn-installer pnpm
).
Dependencies: Functions use the
package.json
next to the blueprint for dependencies by default (
project-level
). Each function can alternatively have its own
package.json
(
function-level
), but a function uses one or the other — never both. See Sanity Functions: Dependencies.
添加文件前,先在项目中搜索是否已有
sanity.blueprint.ts
。如果已有包含已部署函数的文件,将新函数添加到该文件中——即使它不在锁文件所在目录。已有的可用配置优先于以下默认部署规则。仅在从零开始创建新蓝图时遵循以下规则。
找到项目的锁文件(
yarn.lock
pnpm-lock.yaml
package-lock.json
)。创建新蓝图的两条规则:
  1. sanity.blueprint.ts
    必须与锁文件位于同一目录
    。CLI会从锁文件检测包管理器。如果没有锁文件,需在部署命令中添加
    --fn-installer pnpm
    (或
    npm
    /
    yarn
    )参数。
  2. 函数
    src
    路径相对于蓝图文件解析
    。默认情况下,名为
    classify-conversations
    的函数对应蓝图文件旁的
    functions/classify-conversations/
    目录。可在
    defineScheduledFunction
    中使用
    src
    属性指向其他目录。
在单体仓库中如果没有现有蓝图,锁文件位于工作区根目录——因此
sanity.blueprint.ts
functions/
也需放在根目录,与根
package.json
同级。但如果蓝图已存在于子目录(例如
apps/studio/
)且函数可成功部署,使用该位置即可。CLI在正确配置后(例如添加
--fn-installer pnpm
)可在子目录中工作。
依赖项:函数默认使用蓝图文件旁的
package.json
中的依赖项(项目级)。每个函数也可拥有自己的
package.json
(函数级),但一个函数只能使用其中一种方式——不能同时使用两者。查看Sanity Functions: Dependencies了解详情。

Commands

命令

Run from the directory containing
sanity.blueprint.ts
:
CommandPurpose
npx sanity blueprints init
Initialize the blueprint stack (first time only)
npx sanity blueprints promote
Promote to org scope (required for scheduled functions)
npx sanity blueprints doctor
Check blueprint health and flag issues
npx sanity blueprints plan
Preview what deploy will change
npx sanity blueprints deploy
Deploy blueprint and functions
npx sanity functions env add <fn> <key> <value>
Set an env var (after deploy)
npx sanity functions logs <name>
View function logs
npx sanity functions test <name> --with-user-token
Test function locally
在包含
sanity.blueprint.ts
的目录中运行:
命令用途
npx sanity blueprints init
初始化蓝图栈(仅首次使用)
npx sanity blueprints promote
升级到组织范围(定时函数必需)
npx sanity blueprints doctor
检查蓝图健康状态并标记问题
npx sanity blueprints plan
预览部署将产生的变更
npx sanity blueprints deploy
部署蓝图与函数
npx sanity functions env add <fn> <key> <value>
设置环境变量(部署后)
npx sanity functions logs <name>
查看函数日志
npx sanity functions test <name> --with-user-token
本地测试函数

GROQ with Semantic Search

结合语义搜索的GROQ

Sanity Context supports
text::semanticSimilarity()
for semantic ranking:
groq
*[_type == "article" && category == "guides"]
  | score(text::semanticSimilarity("getting started tutorial"))
  | order(_score desc)
  { _id, title, summary }[0...10]
Always use
order(_score desc)
when using
score()
to get best matches first.
Sanity Context支持
text::semanticSimilarity()
进行语义排序:
groq
*[_type == "article" && category == "guides"]
  | score(text::semanticSimilarity("getting started tutorial"))
  | order(_score desc)
  { _id, title, summary }[0...10]
使用
score()
时,务必添加
order(_score desc)
以优先显示最佳匹配结果。

Adapting to Different Stacks

适配不同技术栈

The MCP connection pattern is framework and LLM-agnostic. Whether Next.js, Remix, Express, or Python FastAPI—the HTTP transport works the same. Any LLM provider that supports tool calling will work.
See references/adapting-to-stacks.md for:
  • Framework-specific route patterns (Express, Remix, Python)
  • AI library integrations (LangChain, direct API calls)
See references/system-prompts.md for domain-specific examples (e-commerce, docs, support, content curation).
MCP连接模式与框架和LLM无关。无论是Next.js、Remix、Express还是Python FastAPI——HTTP传输方式完全相同。任何支持工具调用的LLM供应商均可使用。
查看references/adapting-to-stacks.md获取:
  • 框架专属路由模式(Express、Remix、Python)
  • AI库集成(LangChain、直接API调用)
查看references/system-prompts.md获取领域专属示例(电商、文档、客服、内容策划)。

Best Practices

最佳实践

  • Start simple: Build the basic integration first, then add advanced patterns as needed
  • Schema design: Use descriptive field names—agents rely on schema understanding
  • GROQ queries: Always include
    _id
    in projections so agents can reference documents
  • Content filters: Use
    groqFilter
    to scope what the production agent sees — start broad, then narrow based on what it actually needs. The filter is a full GROQ expression (e.g.,
    _type in ["product", "article"]
    )
  • Instructions field: Keep it concise — only include what the auto-generated schema doesn't make obvious. Don't duplicate schema information. See the
    dial-your-context
    skill.
  • System prompts: Be explicit about forbidden behaviors and formatting rules. Less is more — an over-engineered prompt can interfere with the Instructions content. See the
    shape-your-agent
    skill.
  • Package versions: Always use the latest version of
    @sanity/context
    — run
    npm info @sanity/context version
    to get it. For other packages, check the reference
    package.json
    files or use
    npm info <package> version
    . AI SDK and Sanity packages update frequently, and using outdated versions will cause errors that are hard to debug.
  • 从简开始:先完成基础集成,再按需添加高级模式
  • Schema设计:使用描述性字段名称——Agent依赖对schema的理解
  • GROQ查询:在投影中始终包含
    _id
    ,以便Agent可引用文档
  • 内容筛选器:使用
    groqFilter
    限定生产环境Agent的内容访问范围——先设置较广范围,再根据实际需求缩小。筛选器为完整的GROQ表达式(例如
    _type in ["product", "article"]
  • Instructions字段:保持简洁——仅包含自动生成的schema无法体现的信息。不要重复schema内容。查看
    dial-your-context
    技能了解详情。
  • 系统提示词:明确禁止行为与格式规则。少即是多——过度设计的提示词可能干扰Instructions内容。查看
    shape-your-agent
    技能了解详情。
  • 包版本:始终使用
    @sanity/context
    的最新版本——运行
    npm info @sanity/context version
    获取最新版本。对于其他包,查看参考
    package.json
    文件或运行
    npm info <package> version
    。AI SDK与Sanity包更新频繁,使用过时版本会导致难以调试的错误。

Troubleshooting

故障排查

Sanity Context returns errors or no schema

Sanity Context返回错误或无schema

Sanity Context requires a deployed Studio. See Deploy Your Studio for instructions.
Sanity Context需要已部署的Studio。查看Deploy Your Studio获取部署指引。

"401 Unauthorized" from MCP

MCP返回"401 Unauthorized"

The
SANITY_API_READ_TOKEN
is missing or invalid. Generate a new token from the terminal:
bash
npx sanity tokens add "Sanity Context" --role=viewer --yes --json
Or create one at sanity.io/manage → Project → API → Tokens with Viewer role.
SANITY_API_READ_TOKEN
缺失或无效。从终端生成新令牌:
bash
npx sanity tokens add "Sanity Context" --role=viewer --yes --json
或在sanity.io/manage → 项目 → API → 令牌页面创建Viewer权限的令牌。

"No documents found" / Empty results

"No documents found" / 结果为空

Check the Sanity Context document's content filter (
groqFilter
):
  • Is the GROQ filter correct?
  • Are the document types spelled correctly?
  • Are there published documents matching the filter?
检查Sanity Context文档的内容筛选器(
groqFilter
):
  • GROQ筛选器是否正确?
  • 文档类型拼写是否正确?
  • 是否有符合筛选条件的已发布文档?

Tools not appearing

工具未显示

  1. Check that
    mcpClient.tools()
    returns tools (log it)
  2. Ensure the MCP URL is correct (project ID, dataset, and optionally slug)
  3. If using a slug-based URL, verify the Sanity Context document is published
  1. 检查
    mcpClient.tools()
    是否返回工具(可打印日志)
  2. 确认MCP URL正确(项目ID、数据集以及可选的slug)
  3. 如果使用带slug的URL,验证Sanity Context文档已发布