Sanity Context

Connect Sanity Context with the Claude Agent SDK

Connect Sanity Context to a Python or TypeScript agent built with the Claude Agent SDK.

The Claude Agent SDK runs Claude as a general-purpose agent from Python or TypeScript. This guide shows you how to connect an Agent SDK agent to Sanity Context and limit it to the Sanity tools. You'll build a script that loads your schema or Knowledge Base outline into the system prompt, connects to your Context MCP endpoint as a remote HTTP server, and answers a question about your content. The same code works whether the endpoint uses Knowledge Base sources, a dataset source, or both.

Prerequisites

To follow this guide, you need:

  • Context MCP endpoint URL: Shown on the MCP endpoint in the Context app in the Sanity Dashboard. To create an MCP endpoint, see Configure a Context MCP endpoint, or expand Create the endpoint with the Sanity CLI (optional) at the end of this section.
  • Organization API token: Create one in Manage under API > Tokens at the organization level. Under Organization permissions, select Context with the Viewer role. Project tokens don't work.
  • Anthropic API key: The SDK reads it from ANTHROPIC_API_KEY.
  • Node.js 22.18 or later for TypeScript, or Python 3.10 or later for Python. Node.js 22.18 and later run .ts files directly.

Both SDKs bundle the Claude Code runtime they drive, so there's nothing else to install.

Create the endpoint with the Sanity CLI (optional)

You can create a Knowledge Base and an MCP endpoint from the Sanity CLI instead of the Dashboard. If you haven't signed in, run npx sanity@latest login. You still create the organization token in Manage. Replace ORGANIZATION_ID, PROJECT_ID, and KNOWLEDGE_BASE_ID with your own values:

mcp create prints the endpoint URL to use as SANITY_CONTEXT_MCP_URL. To serve a live dataset through a dataset source instead, replace --knowledge-base KNOWLEDGE_BASE_ID with -p PROJECT_ID -d production. See the Context CLI command reference for every flag.

Install dependencies

Set the module type in package.json so Node.js loads agent.ts as an ES module and the top-level await runs:

Set environment variables

Create a .env file next to agent.ts or agent.py. Replace each placeholder with your own value:

Create the agent

Create agent.ts or agent.py next to .env. The script works in three stages:

  • Fetch initial context from the /initial-context HTTP endpoint and add it to the system prompt. It's the schema overview for a dataset source, the Knowledge Base outline for Knowledge Base sources, or both if the endpoint has both, plus the endpoint's instructions. The agent writes accurate queries from the first turn and saves a tool call per conversation. For details, see Inline initial context into your system prompt.
  • Connect to the MCP endpoint by passing it as an http server with your organization token in the headers. The SDK names its tools mcp__sanity__TOOL_NAME, where TOOL_NAME is the Context MCP tool name. When the initial context is in the prompt, the disallowed tools list hides mcp__sanity__initial_context. If the fetch failed, the agent keeps the tool and calls it instead.
  • Run the agent with query(). The first message reports each MCP server's status, and the script stops unless Sanity is connected. Otherwise the agent would run without your content.

The Agent SDK is a general-purpose agent, so the options in the script narrow it to a content agent:

  • tools: [] (tools=[] in Python) removes the built-in tools, such as Bash, file editing and web fetch.
  • allowedTools: ['mcp__sanity'] approves every tool from the Sanity server, and the dontAsk permission mode denies anything else without prompting. Without the allow rule, every Sanity tool call is denied.
  • settingSources: [] and strictMcpConfig: true (setting_sources=[] and strict_mcp_config=True in Python) ignore local Claude Code settings, CLAUDE.md files, and other MCP servers, so the agent behaves the same on every machine.

Run the agent

Pass a question as the first argument, or leave it out to ask "What content do we have?"

The agent calls the Sanity tools it needs, then prints its answer to the terminal. If the run fails, match the message against the list in Troubleshoot common errors. To confirm the initial context loaded, ask "What content do you have access to?" With the initial context in the system prompt, the agent answers without calling a tool first.

Dataset and Knowledge Base sources

The same code works with an endpoint that serves Knowledge Bases. What changes is what the endpoint returns:

Dataset sourceKnowledge Base source
Content sourceA datasetOne or more Knowledge Bases
Initial contextSchema overviewOutline of each Knowledge Base, with its ID
Tools after filteringmcp__sanity__schema_explorer, mcp__sanity__groq_query, mcp__sanity__array_field_readermcp__sanity__knowledge_base_search, mcp__sanity__knowledge_base_read

An endpoint can have one dataset source and several Knowledge Base sources. If it has both types, it serves the tools from both columns, and initial context contains both the schema overview and the Knowledge Base outline. See Context MCP tools and Context MCP source types.

Troubleshoot common errors

These are the most common errors and how to fix them:

  • [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///…/agent.ts is not specified and it doesn't parse as CommonJS. (TypeScript): The agent still runs, but package.json doesn't set the module type. Run npm pkg set type=module.
  • Missing environment variable SANITY_CONTEXT_MCP_URL (TypeScript) or KeyError: 'SANITY_CONTEXT_MCP_URL' (Python): The .env file is missing or wasn't loaded. In TypeScript, run with --env-file=.env. In Python, load_dotenv() looks in the script's folder, then in each parent folder.
  • Sanity Context MCP server status: failed, after a 401 on the initial context fetch: The token is missing, invalid, or belongs to another organization. Check the organization ID in the URL too.
  • 403 from the MCP connection with JSON-RPC error -32007 on an endpoint with a dataset source, or -32006 on an endpoint with only Knowledge Base sources, or the same 403 from the /initial-context fetch with code contextGrantRequired or knowledgeBaseAccessDenied. The messages are "Serving a dataset requires an organization API token with Context access ('sanity.knowledge-base.read'). Create one under your organization's API settings in Manage." (dataset source) and "No access to knowledge base '<knowledge base ID>'. Requires one of: sanity.knowledge-base.read." (Knowledge Base sources only; <knowledge base ID> is a placeholder for the Knowledge Base's ID): On an endpoint with a dataset source, the token isn't an organization API token with Context Viewer permissions. On an endpoint with only Knowledge Base sources, the token has no read access to the Knowledge Base the message names. Project tokens are refused however broad their permissions. Create an organization token as described in Prerequisites.
  • Invalid API key or Not logged in · Please run /login: Set ANTHROPIC_API_KEY in the .env file.
  • The agent answers that permission to run groq_query was denied: The allowed tools list is missing, or names a different server than the key in the MCP servers config.
  • No matching distribution found for claude-agent-sdk: Your Python is older than 3.10, the minimum the SDK supports. The Python that ships with macOS is 3.9, so install a newer one and recreate the virtual environment.

Next steps

  • Sanity Context patterns and best practices: Production patterns for public assistants, personalized agents, and multi-backend setups.
  • Inline initial context into your system prompt: Control what the inlined payload contains and keep it fresh in long-running agents.
  • Knowledge Bases: Organize your datasets, website and files into verified facts, each cited to its source. Context flags conflicting sources for your team to resolve before agents see them.
  • Agent skills: Install the Sanity Context skills, which walk a coding agent such as Claude Code through creating an endpoint and building an agent.

Was this page helpful?