MCPInstall

sanity-singletons

Configure singleton documents in a Sanity Studio using the document.singletons registry. Use when a developer wants a fixed-id document (settings, navigation, footer) edited in place, hidden from the default content list, with no "create new" or "duplicate" affordances — or when migrating a userland singleton implementation or a third-party singleton plugin (e.g. sanity-plugin-singleton-management) to the first-class API.

Installs
144
Last 24h
+11
Trending rank
#8173
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/sanity-io/agent-toolkit --skill sanity-singletons
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads sanity-singletons automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Sanity Singletons

A "singleton" is a document with a fixed id that can be created exactly once. Common examples: site settings, navigation, footer content. Studio supports singletons as a first-class primitive via the document.singletons configuration registry plus a small set of Structure Tool helpers.

Requires sanity 6.17.0 or later. Check the installed version in the lockfile before using this API. On older Studios, either upgrade first or use the userland pattern (fixed documentId in a custom structure, plus manual newDocumentOptions and duplicate filtering) described in sanity-best-practices → studio-structure.

When to use this skill

  • A developer asks how to create a "settings document" or "singleton".
  • A studio configuration needs a document.singletons registry entry.
  • Structure Tool needs to render a singleton as a list item or document pane.
  • You're migrating an existing userland singleton implementation to the first-class API.
  • You're migrating from a third-party singleton plugin such as sanity-plugin-singleton-management (or its predecessor sanity-plugin-singleton-tools).

Registering a singleton

Singletons are registered in configuration, not on the schema type. A singleton definition binds a definition id to a document id and a schema type:

import {defineConfig, defineSingleton} from 'sanity'

export default defineConfig({
  schema: {
    types: [/* siteSettings and campaign are ordinary document types */],
  },
  document: {
    singletons: [
      // String shorthand — expands to
      // {id: 'siteSettings', documentId: 'siteSettings', schemaType: 'siteSettings'}
      'siteSettings',

      // Definition object. `defineSingleton` is an optional typed identity
      // helper; a plain object literal works too. `id` is omitted here, so it
      // inherits each `documentId`.
      defineSingleton({
        documentId: 'springCampaign',
        schemaType: 'campaign',
        title: 'Spring campaign', // optional display metadata
        initialValue: {season: 'spring'}, // optional per-singleton initial value
      }),
      defineSingleton({
        documentId: 'summerCampaign',
        schemaType: 'campaign',
        title: 'Summer campaign',
        initialValue: {season: 'summer'},
      }),
    ],
  },
})

Key facts:

  • defineSingleton produces a singleton definition, not a document schema. The schema type it references is defined separately with defineType and needs no singleton-specific configuration.
  • Multiple singletons may share a schema type (like the two campaigns above), each with its own title, icon, and initialValue (falling back to the schema type's), and a shared schema type may also back ordinary documents.
  • The definition id is the singleton's stable identity, and it is optional — it inherits documentId when omitted. Structure code references it (S.listItem().singleton('springCampaign')). Set it explicitly only to be verbose, to guard against future collisions, or to address a singleton universally when different workspaces or environments map it to different document ids.
  • A resolver function is also accepted: singletons: (prev, context) => [...prev, ...]. Resolvers only ever receive fully resolved definitions (string shorthands are expanded first).

Validation at config-resolution time (all failures aggregate into one ConfigResolutionError):

  • id: non-empty, unique across definitions (inherited ids count — an explicit id may not collide with another definition's inherited one). Used verbatim as a Structure Tool node id, so it is limited to [a-zA-Z0-9._-] and may not start with __edit__. It also may not match the name of a document type that no singleton claims, since the default content list keys both by id (the string shorthand never trips this — the type it names is claimed by the definition itself).
  • documentId: non-empty, unique, published-id shaped (no drafts. / versions. prefix, only [a-zA-Z0-9._-]).
  • schemaType: must name an existing document type. Need not be unique.
  • Templates: an untagged template must not reuse a definition id (the generated singleton template claims it); at most one template may carry a given singleton tag; tags must reference registered definitions.

What Studio does automatically

  1. Generates a dedicated initial value template per singleton — tagged with the definition id via ResolvedTemplate.singleton, value from definition.initialValue ?? schemaType.initialValue — instead of the plain per-type template, and removes tagged templates from every "create new" surface (global create menu, structure panes, reference inputs). The tagged template stays in source.templates, so opening the singleton before it exists still applies its initial value.
  2. Injects context.singleton (the definition id) into document-scoped configuration contexts — document.actions, badges, inspectors, field actions, comments.enabled, askToEdit.enabled — looked up by published document id, so drafts and release versions of the singleton match, however the document was opened (structure, intent, deep link, search).
  3. Filters the duplicate document action, after all user resolvers run, so it cannot be reintroduced via document.actions.
  4. Hides the schema type from the implicit default content list in Structure Tool, and appends the singleton itself to that list — one item per definition, after the document type lists, in registration order, each equivalent to S.listItem().singleton(id). A studio that has not configured Structure Tool needs no structure code at all. This applies only to the default structure; a structure resolver replaces it wholesale.

What Studio deliberately does not do:

  • Delete, unpublish, and discard stay available. Deleting a singleton is a legitimate "reset": structure still points at the fixed id, and editing recreates the document. To hide delete as well: document: {actions: (prev, context) => (context.singleton ? prev.filter((action) => action.action !== 'delete') : prev)}.
  • Explicit structure is never filtered. S.documentTypeList(typeName) works for singleton schema types and intentionally lists the singleton documents alongside ordinary ones.
  • No warning for "dangling" singletons. Structure resolves lazily, so Studio cannot detect a registered singleton that a custom structure never adds. (The default structure adds them all, so this only affects studios with a structure resolver.) Any heuristic short of eager resolution would misfire, because manual S.document().documentId(...).schemaType(...) wiring is supported. In a custom structure, always pair a registry entry with a structure entry.

Surfacing singletons in Structure Tool

With the default structure there is nothing to do — registered singletons are appended to the top-level content list automatically.

In a custom structure (any studio passing a structure resolver to structureTool()), add them explicitly. All helpers are keyed by definition id and throw a SerializeError for unknown ids.

Watch for this trap: S.documentTypeListItems(), the usual way to reproduce the default lists inside a custom structure, excludes singleton schema types and does not add singleton items. S.list().items([...S.documentTypeListItems()]) therefore drops every singleton. Use .singletons() alongside it:

S.list().id('__root__').title('Content').items(S.documentTypeListItems()).singletons()
// 1. Highest level: a list of singletons — a given set, or all of them.
S.list().id('singletons').title('Singletons').singletons(['siteSettings', 'springCampaign'])
S.list().id('singletons').title('Singletons').singletons()

// 2. A single list item (title/icon default from the definition, then the schema type).
S.listItem().singleton('siteSettings')

// 3. Low level: just the document pane.
S.listItem().title('Settings').id('settings').child(S.document().singleton('siteSettings'))

Composition rules:

  • Every default is overridable by normal chaining: S.listItem().singleton('siteSettings').title('Global settings'), S.document().singleton('siteSettings').documentId('override').
  • Titles are not disambiguated for you. The list item id defaults to the definition id (unique by construction), but the title falls back to the schema type's, so singletons sharing a schema type share a label. Give each definition a title — it applies everywhere the singleton is rendered, including S.list().singletons(), which has no per-item overrides.
  • S.document().singleton() pins the singleton's tagged initial value template so its initial value applies even when the type has several templates; override with .initialValueTemplate(...).
  • S.list().singletons() returns a builder without .items(). Calling .items() afterwards would replace the whole array and silently drop the singleton items, so the type forbids it. Call .items([...]) before .singletons([...]), or put S.listItem().singleton() entries inside a regular .items() array. Repeated .singletons() calls append.
  • singletons() with no argument means every registered definition (registration order, including plugin-registered ones); singletons([]) means none. Combining it with a hand-written S.listItem().singleton(id) in the same list adds that singleton twice and fails with a duplicate-id SerializeError — pass an explicit array when mixing.
  • S.documentListItem().singleton(id) renders a live document preview instead of a static title, and defaults its id to the definition's documentId (not the definition id), because a document list item's id is the document it previews. Prefer plain S.listItem() when the singleton document may not exist yet.

Shared schema types and the "create new" escape hatch

Declaring a singleton over schema type T replaces T's plain per-type template with the singleton's tagged template, so T disappears from create menus. If ordinary T documents should stay creatable, define an explicit untagged template — any id works, including T itself, since the plain template no longer exists:

schema: {
  templates: (prev) => [
    ...prev,
    {id: 'campaign-non-singleton', title: 'Campaign', schemaType: 'campaign', value: {}},
  ],
},

This is the one place the default structure is not enough on its own: it surfaces the singletons over the shared type, but the type stays filtered, so ordinary documents of it remain unlisted while the structure looks complete. A shared schema type always needs an explicit S.documentTypeListItem(typeName) somewhere in the structure. (A future allowNonSingletonDocuments flag on the definition will replace both the escape-hatch template and this structure entry.)

The singleton tag carries the semantics: templates with it are never create options; templates without it always are. The tag lives on ResolvedTemplate — the resolved shape in source.templates — not on the authoring Template type, so developers never set it directly. To customise a singleton's initial value via schema.templates, find the singleton's template by id (equal to the definition id) and spread it ({...template, value}) — the spread preserves the tag at runtime, keeping it out of create menus. (Setting initialValue on the definition itself is usually simpler.)

Reading singletons from plugins

  • The resolved registry is available at source.document.singletons (useSource().document.singletons).
  • Document-scoped resolvers receive context.singleton (the definition id; documentId and schemaType are already on the context).

Migrating a userland singleton setup

Typical userland implementations combine three pieces; each is subsumed by the registry:

Userland techniqueFirst-class replacement
document.newDocumentOptions filtering out the typeAutomatic (tagged singleton templates are never create options)
document.actions filtering duplicateAutomatic (terminal, non-bypassable)
Custom structure with S.document().schemaType(x).documentId(y)Keep, or simplify to S.listItem().singleton(id)

Migration steps:

  1. Add the singleton to document.singletons (string shorthand when id, document id, and type name are all identical).
  2. Delete the manual newDocumentOptions and duplicate filtering for that type.
  3. Replace the manual structure wiring with S.listItem().singleton(id) (or keep the manual wiring — it remains fully supported; ensure the documentId/schemaType pair matches the definition so context.singleton resolves). If the only reason a custom structure existed was to surface the singletons, delete the resolver entirely and let the default structure do it.
  4. If the schema type is only used by the singleton, nothing else changes. If it's shared with ordinary documents, add an explicit untagged template to keep them creatable, and S.documentTypeList(typeName) to keep them listed.

Migrating from sanity-plugin-singleton-management

sanity-plugin-singleton-management (a maintained fork of sanity-plugin-singleton-tools, with an identical API) marks schema types with options: {singleton: true}, registers a singletonTools() plugin that filters new-document options and document actions, and ships three structure helpers. Every piece maps directly onto the first-class API:

Plugin techniqueFirst-class replacement
options: {singleton: true} on the schema typeA document.singletons entry (delete the schema option — it has no first-class meaning)
singletonTools() plugin in plugins: [...]Delete (creation and duplicate prevention are automatic)
singletonDocumentListItem({S, context, type, title, id, icon})S.listItem().singleton(<definition id>) (title/icon defaults come from the definition, then the schema type)
singletonDocumentListItems({S, context})S.list().singletons() (or nothing at all, if using the default structure)
filteredDocumentListItems({S, context})...S.documentTypeListItems() — singleton schema types are excluded automatically

Document id compatibility (the critical detail): the plugin's document id defaults to the schema type name (S.document().schemaType(type).id(id ?? type)), so a plugin singleton mySingleton edits the document mySingleton. The string shorthand (singletons: ['mySingleton']) produces exactly that document id — existing content keeps working with no data migration. If the plugin call passed an explicit id, carry it over as the definition's documentId.

Migration steps:

  1. For each schema type with options: {singleton: true}: remove the option, and register the type in document.singletons — the string shorthand when the plugin used the default id, otherwise {documentId: <the explicit id>, schemaType: <type>}.

  2. Remove singletonTools() from plugins and uninstall the package.

  3. Replace the structure helpers per the table above. The plugin passed {S, context} around; the first-class helpers need neither — they read the registry from the builder's own context.

  4. Note a deliberate behavioural difference: the plugin allowlists actions (publish, discardChanges, restore), hiding delete and unpublish. The first-class API only removes duplicate — deleting a singleton is a legitimate "reset". To preserve the plugin's stricter behaviour, add:

    document: {
      actions: (prev, context) =>
        context.singleton
          ? prev.filter(({action}) =>
              ['publish', 'discardChanges', 'restore'].includes(action as string),
            )
          : prev,
    },
    

    Only add this if the stricter behaviour is genuinely wanted — otherwise prefer the first-class default.

  5. If the plugin's singletonDocumentListItem was used to render multiple singletons of the same schema type (its title/id overrides), register one definition per document id — {documentId, schemaType, title} — which is the first-class model for exactly that case.

Reference

Source lives in the sanity-io/sanity monorepo:

FAQ

What does the sanity-singletons skill do?

Configure singleton documents in a Sanity Studio using the document.singletons registry. Use when a developer wants a fixed-id document (settings, navigation, footer) edited in place, hidden from the default content list, with no "create new" or "duplicate" affordances — or when migrating a userland singleton implementation or a third-party singleton plugin (e.g. sanity-plugin-singleton-management) to the first-class API.

How do I install sanity-singletons?

Run npx skills add https://github.com/sanity-io/agent-toolkit --skill sanity-singletons in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/sanity-singletons/ (personal) or .claude/skills/sanity-singletons/ (project).

Which AI agents can use sanity-singletons?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is sanity-singletons safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains sanity-singletons?

It is published by sanity-io in sanity-io/agent-toolkit. It has 144 recorded installs.

More from sanity-io/agent-toolkit

View all →

sanity-best-practices

sanity-io/agent-toolkit

Sanity development best practices for schema design, GROQ queries, TypeGen, Visual Editing, images, Portable Text, Studio structure, localization, migrations, Sanity Functions, webhooks, Blueprints, and framework integrations such as Next.js, Nuxt, Astro, Remix, SvelteKit, Angular, Hydrogen, the App SDK, and Studios or apps running in the Sanity Dashboard (defineApplication). Use this skill whenever working with Sanity schemas, defineType or defineField, GROQ or defineQuery, content modeling, Presentation or preview setups, Sanity-powered frontend integrations, event-driven content automation, documentEventHandler, defineDocumentFunction, defineMediaLibraryAssetFunction, @sanity/functions, @sanity/blueprints, sanity.blueprint.ts, event-driven content automation, or when reviewing and fixing a Sanity codebase.

OfficialCode Quality & Workflow31.9K installs

sanity-migration

sanity-io/agent-toolkit

Plans, implements, and reviews migrations from other CMSes and content systems into Sanity. Use when migrating or replatforming to Sanity from AEM, Adobe Experience Manager, Contentful, Strapi, Webflow, WordPress, Payload, Drupal, Markdown/MDX/frontmatter files, WXR/XML exports, CMS APIs, database dumps, static HTML, or when designing extraction, transformation, Portable Text conversion, asset migration, redirects, validation, and cutover workflows.

seo-aeo-best-practices

sanity-io/agent-toolkit

SEO and AEO best practices for metadata, Open Graph, sitemaps, robots.txt, hreflang, JSON-LD structured data, EEAT, and content optimized for search engines and AI answer surfaces. Use this skill when implementing page SEO, technical SEO, schema markup, international SEO, AI-overview readiness, or improving content for Google, ChatGPT, Perplexity, and similar assistants.

OfficialMarketing & SEO7.3K installs

content-modeling-best-practices

sanity-io/agent-toolkit

Structured content modeling guidance for schema design, content architecture, content reuse, references versus embedded objects, separation of concerns, and taxonomies across Sanity and other headless CMSes. Use this skill when designing or refactoring content types, deciding field shapes, debating reusable versus nested content, planning omnichannel content models, or reviewing whether a schema is too page-shaped or presentation-driven.

OfficialCode Quality & Workflow4.9K installs

Content experimentation and A/B testing guidance covering experiment design, hypotheses, metrics, sample size, statistical foundations, CMS-managed variants, and common analysis pitfalls. Use this skill when planning experiments, setting up variants, choosing success metrics, interpreting statistical results, or building experimentation workflows in a CMS or frontend stack.

OfficialCode Quality & Workflow3.8K installs

portable-text-serialization

sanity-io/agent-toolkit

Render and serialize Portable Text to React, Svelte, Vue, Astro, HTML, Markdown, and plain text. Use when implementing Portable Text rendering in any frontend framework, building custom serializers for non-standard block types, converting Portable Text to HTML strings server-side, converting Portable Text to Markdown, extracting plain text from Portable Text, or troubleshooting rendering issues with marks, blocks, lists, or custom types.

OfficialFrontend & Design2.9K installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs