Build with AI

Connect Sanity Context with Vercel AI SDK

Connect Sanity Context to a TypeScript agent using the Vercel AI SDK and Anthropic.

This example connects Sanity Context to a TypeScript agent using the Vercel AI SDK. It fetches initial context for schema awareness, connects to the MCP endpoint, and runs an agent that can query your content.

Before you start

You need a Sanity Context MCP endpoint. If you haven't set one up yet, start with Sanity Context. You'll need:

  • MCP endpoint URL: Shown in the Sanity Context document in Studio.
  • Sanity API read token: Create one at sanity.io/manage.
  • Anthropic API key: The AI SDK reads it from ANTHROPIC_API_KEY.
  • Node.js 22.18 or later: Runs TypeScript files directly. Earlier versions need npx tsx and a package such as dotenv.

Install dependencies

All three packages are ESM-only. Set the module type in package.json so the top-level await calls in the example compile:

Set environment variables

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

Full example

Connect to the MCP endpoint, fetch initial context, and run the agent:

Run the agent

Node reads the .env file with --env-file:

How it works

Every Sanity Context integration follows three steps:

  • Fetch initial context via the /initial-context HTTP endpoint and inject it into your system prompt. This gives the agent a compressed schema overview so it can write accurate queries from the start — and saves a tool call on every conversation.
  • Connect to MCP and get tools: Authenticate with your Sanity API read token. Remove the initial_context tool from the set since you've already fetched it.
  • Call the LLM with the tools and system prompt. The agent will make tool calls as it explores your content.

Common errors

Three failures account for most first runs:

  • error TS1309: The current file is a CommonJS module and cannot use 'await' at the top level: Set "type": "module" in package.json.
  • TypeError: Cannot read properties of undefined (reading 'replace'): The environment variables aren't loaded. The ! assertions are erased at runtime, so a missing value surfaces at first use rather than at startup.
  • Anthropic API key is missing. Pass it using the 'apiKey' parameter or the ANTHROPIC_API_KEY environment variable.: Add ANTHROPIC_API_KEY to the .env file.

Next steps

Was this page helpful?