Skip to main content
Glama

contentrain_model_save

Create or update a content model definition with automated git commits for structured content management.

Instructions

Create or update a model definition. Changes are auto-committed to git — do NOT manually edit .contentrain/ files after calling this tool.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
idYesModel ID (kebab-case, e.g. "blog-post")
nameYesHuman-readable name
kindYesModel kind
domainYesContent domain (e.g. "blog", "marketing", "system")
i18nYesWhether this model supports localization
descriptionNoModel description
fieldsNoField definitions (not needed for dictionary)
content_pathNoFramework-relative path for content files (e.g. "content/blog", "locales"). When set, content is written here instead of .contentrain/content/
locale_strategyNoHow locale is encoded in file names. Default: "file"

Implementation Reference

  • Handler implementation for contentrain_model_save tool.
    server.tool(
      'contentrain_model_save',
      'Create or update a model definition. Changes are auto-committed to git — do NOT manually edit .contentrain/ files after calling this tool.',
      {
        id: z.string().describe('Model ID (kebab-case, e.g. "blog-post")'),
        name: z.string().describe('Human-readable name'),
        kind: z.enum(['singleton', 'collection', 'document', 'dictionary']).describe('Model kind'),
        domain: z.string().describe('Content domain (e.g. "blog", "marketing", "system")'),
        i18n: z.boolean().describe('Whether this model supports localization'),
        description: z.string().optional().describe('Model description'),
        fields: fieldDefSchema.optional().describe('Field definitions (not needed for dictionary)'),
        content_path: z.string().optional().describe('Framework-relative path for content files (e.g. "content/blog", "locales"). When set, content is written here instead of .contentrain/content/'),
        locale_strategy: z.enum(['file', 'suffix', 'directory', 'none']).optional().describe('How locale is encoded in file names. Default: "file"'),
      },
      async (input) => {
        const config = await readConfig(projectRoot)
        if (!config) {
          return {
            content: [{ type: 'text' as const, text: JSON.stringify({ error: 'Project not initialized. Run contentrain_init first.' }) }],
            isError: true,
          }
        }
    
        // Validate
        const errors = validateModel(input)
        if (errors.length > 0) {
          return {
            content: [{ type: 'text' as const, text: JSON.stringify({ error: 'Validation failed', details: errors }) }],
            isError: true,
          }
        }
    
        // Reject invalid locale_strategy + i18n combinations
        if (input.locale_strategy === 'none' && input.i18n !== false) {
          return {
            content: [{ type: 'text' as const, text: JSON.stringify({
              error: 'locale_strategy "none" requires i18n:false. The "none" strategy stores a single file without locale encoding, which is incompatible with multi-locale content. Use "file", "suffix", or "directory" for i18n models.',
            }) }],
            isError: true,
          }
        }
    
        // Branch health gate
        const health = await checkBranchHealth(projectRoot)
        if (health.blocked) {
          return {
            content: [{ type: 'text' as const, text: JSON.stringify({
              error: health.message,
              action: 'blocked',
              hint: 'Merge or delete old contentrain/* branches before creating new ones.',
            }, null, 2) }],
            isError: true,
          }
        }
    
        const existing = await readModel(projectRoot, input.id)
        const action = existing ? 'updated' : 'created'
    
        const model: ModelDefinition = {
          id: input.id,
          name: input.name,
          kind: input.kind,
          domain: input.domain,
          i18n: input.i18n,
          description: input.description,
          fields: input.fields as ModelDefinition['fields'],
          content_path: input.content_path,
          locale_strategy: input.locale_strategy,
        }
    
        const branch = buildBranchName('model', input.id)
        const tx = await createTransaction(projectRoot, branch)
    
        try {
          await tx.write(async (wt) => {
            await writeModel(wt, model)
          })
    
          await tx.commit(`[contentrain] ${action}: ${input.id}`)
          const gitResult = await tx.complete({ tool: 'contentrain_model_save', model: input.id })
    
          const defaultLocale = config.locales.default
          // Build accurate content path using path resolvers
          const contentDir = resolveContentDir(projectRoot, model)
          const contentPath = model.content_path ?? `.contentrain/content/${input.domain}/${input.id}`
          let exampleFilePath: string
          if (model.kind === 'document') {
            exampleFilePath = resolveMdFilePath(contentDir, model, defaultLocale, '{slug}')
          } else {
            exampleFilePath = resolveJsonFilePath(contentDir, model, defaultLocale)
          }
          // Make the path relative for display
          const displayPath = exampleFilePath.replace(projectRoot + '/', '').replace(projectRoot, '')
          const importSnippet: Record<string, string> = {
            generic: `import data from '${displayPath}'`,
          }
          if (config.stack === 'nuxt') {
            importSnippet['nuxt'] = model.kind === 'document'
              ? `const { data } = await useAsyncData(() => queryContent('${model.domain}/${model.id}').locale('${defaultLocale}').find())`
              : `const { data } = await useFetch('/api/content/${model.id}?locale=${defaultLocale}')`
          }
    
          return {
            content: [{ type: 'text' as const, text: JSON.stringify({
              status: 'committed',
              message: 'Model saved and committed to git. Do NOT manually edit .contentrain/ files.',
              action,
              model: input.id,
              validation: { valid: true, errors: [] },
              git: { branch, action: gitResult.action, commit: gitResult.commit },
              context_updated: true,
              content_path: contentPath + '/',
              example_file: displayPath,
              import_snippet: importSnippet,
              next_steps: ['Add content with contentrain_content_save'],
            }, null, 2) }],
          }
        } catch (error) {
          await tx.cleanup()
          return {
            content: [{ type: 'text' as const, text: JSON.stringify({
              error: `Model save failed: ${error instanceof Error ? error.message : String(error)}`,
            }) }],
            isError: true,
          }
        } finally {
          await tx.cleanup()
        }
      },
    )
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It successfully discloses the git auto-commit side effect and the prohibition against manual file editing, but omits error handling behavior, return value structure, and whether updates are partial or full replacements. This leaves significant behavioral gaps for a structural mutation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences with zero waste: first establishes purpose, second delivers a critical behavioral warning. The information is perfectly front-loaded and appropriately terse for the complexity level.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (nested field definitions with 27 types, 9 parameters) and lack of annotations or output schema, the description provides minimal viable coverage. It successfully flags the git integration quirk but fails to describe return values, error conditions, or the create-vs-update determination logic (implied by ID presence but not explained).

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, with detailed descriptions for all 9 parameters including the complex nested 'fields' object and enum values. The description adds no additional parameter-specific guidance, meeting the baseline expectation when the schema is self-documenting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description explicitly states 'Create or update a model definition,' providing a specific verb pair and resource type. It clearly distinguishes this as a model-level operation (schema definition) rather than content operations, differentiating it from siblings like contentrain_content_save.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides one critical safety constraint ('do NOT manually edit .contentrain/ files'), but lacks explicit guidance on when to use this versus contentrain_model_delete or how to choose between create vs update semantics. The workflow context (git auto-commit) is mentioned but not fully contextualized.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Contentrain/ai'

If you have feedback or need assistance with the MCP directory API, please join our Discord server