Skip to main content
Glama

cms_get_block

Retrieve a CMS block from Magento by providing its block ID.

Instructions

Get a CMS block by ID.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsNoAction parameters as a JSON object

Implementation Reference

  • The handler for the 'cms.get_block' tool. It validates params via CmsGetBlockSchema, then calls the Magento API GET /V1/cmsBlock/{block_id}. Returns CMS block data for the given block ID.
    {
      name: 'cms.get_block',
      description: 'Get a CMS block by ID.',
      riskTier: RiskTier.Safe,
      requiresAuth: true,
      handler: async (params: Record<string, unknown>, context: ActionContext) => {
        const validated = CmsGetBlockSchema.parse(params);
        const client = context.getClient();
        const storeCode = validated.scope?.store_view_code;
        return await client.get(`/V1/cmsBlock/${validated.block_id}`, undefined, storeCode);
      },
    },
  • The Zod input schema for 'cms_get_block'. Expects: block_id (number, int) and optional scope (store_view_code).
    export const CmsGetBlockSchema = z.object({
      block_id: z.number().int(),
      scope: StoreScopeSchema.optional(),
    });
  • src/index.ts:76-159 (registration)
    Registration of all actions as MCP tools. The 'cms.get_block' action is registered as 'cms_get_block' (dots replaced with underscores) via mcpServer.tool().
    for (const action of allActions) {
      // Convert dots to underscores for MCP tool names (e.g. "auth.login" -> "auth_login")
      const toolName = action.name.replace(/\./g, '_');
    
      mcpServer.tool(
        toolName,
        action.description,
        { params: z.record(z.unknown()).optional().describe('Action parameters as a JSON object') },
        async (args) => {
          const params = (args.params || {}) as Record<string, unknown>;
    
          // Check authentication
          if (action.requiresAuth) {
            const token = sessionStore.getToken(sessionId);
            if (!token) {
              return {
                content: [{ type: 'text' as const, text: JSON.stringify({ error: { code: 'NOT_AUTHENTICATED', message: 'Not authenticated. Call auth_login first.' } }, null, 2) }],
                isError: true,
              };
            }
          }
    
          // Build action context
          const context: ActionContext = {
            sessionId,
            getToken: () => sessionStore.getToken(sessionId),
            getBaseUrl: () => sessionStore.getBaseUrl(sessionId),
            getDefaultScope: () => sessionStore.getDefaultScope(sessionId),
            getOAuthCredentials: () => sessionStore.getOAuthCredentials(sessionId),
            getClient: () => {
              const baseUrl = sessionStore.getBaseUrl(sessionId);
              const token = sessionStore.getToken(sessionId);
              if (!baseUrl) throw new Error('No active session');
              const client = new MagentoRestClient(baseUrl, token);
              const oauth = sessionStore.getOAuthCredentials(sessionId);
              if (oauth) client.setOAuth(oauth);
              return client;
            },
            username: sessionStore.getUsername(sessionId),
          };
    
          try {
            const result = await action.handler(params, context);
    
            // Audit log
            const auditRecord: AuditRecord = {
              timestamp: new Date().toISOString(),
              username: context.username,
              action: action.name,
              scope: context.getDefaultScope(),
              params,
              result_summary: summarizeResult(result),
              plan_id: (params['plan_id'] as string) || null,
              reason: (params['reason'] as string) || null,
            };
            auditLogger.log(auditRecord);
    
            return {
              content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
            };
          } catch (err) {
            const errorMessage = err instanceof Error ? err.message : String(err);
    
            // Audit the error
            const auditRecord: AuditRecord = {
              timestamp: new Date().toISOString(),
              username: context.username,
              action: action.name,
              scope: null,
              params,
              result_summary: `ERROR: ${errorMessage}`,
              plan_id: null,
              reason: null,
            };
            auditLogger.log(auditRecord);
    
            return {
              content: [{ type: 'text' as const, text: JSON.stringify({ error: errorMessage }, null, 2) }],
              isError: true,
            };
          }
        },
      );
    }
  • src/index.ts:57-58 (registration)
    The createCmsActions function is called to collect all CMS action definitions including 'cms.get_block'.
    ...createCmsActions(planStore, guardrails, config),
    ...createSeoActions(planStore, guardrails, config),
  • The action definition object for 'cms.get_block' within the createCmsActions function array.
      // ── Get Block ─────────────────────────────────────────────────────────
      {
        name: 'cms.get_block',
        description: 'Get a CMS block by ID.',
        riskTier: RiskTier.Safe,
        requiresAuth: true,
        handler: async (params: Record<string, unknown>, context: ActionContext) => {
          const validated = CmsGetBlockSchema.parse(params);
          const client = context.getClient();
          const storeCode = validated.scope?.store_view_code;
          return await client.get(`/V1/cmsBlock/${validated.block_id}`, undefined, storeCode);
        },
      },
    
      // ── Prepare Bulk Update Blocks ────────────────────────────────────────
      {
        name: 'cms.prepare_bulk_update_blocks',
        description: 'Prepare a bulk update for CMS blocks.',
        riskTier: RiskTier.Risk,
        requiresAuth: true,
        handler: async (params: Record<string, unknown>, context: ActionContext) => {
          const validated = CmsPrepareBulkUpdateBlocksSchema.parse(params);
    
          guardrails.enforceAllowedFields(
            Object.keys(validated.updates),
            config.allowedCmsBlockUpdateFields,
            'CMS block update',
          );
    
          const client = context.getClient();
          const blocks = await resolveMatchingBlocks(client, validated.match);
    
          const sampleDiffs = blocks.slice(0, 5).map((b: Record<string, unknown>) => {
            const diff: Record<string, { from: unknown; to: unknown }> = {};
            for (const [field, newValue] of Object.entries(validated.updates)) {
              diff[field] = { from: b[field], to: newValue };
            }
            return { block_id: b['id'], title: b['title'], changes: diff };
          });
    
          const blockIdentifiers: Record<number, string> = {};
          for (const b of blocks) {
            blockIdentifiers[b['id'] as number] = String(b['identifier'] || '');
          }
    
          const plan = planStore.create(
            'cms.commit_bulk_update_blocks',
            {
              block_ids: blocks.map((b: Record<string, unknown>) => b['id']),
              block_identifiers: blockIdentifiers,
              updates: validated.updates,
              scope: validated.scope,
            },
            blocks.length,
            config.planExpiryMinutes,
            sampleDiffs,
          );
    
          return {
            plan_id: plan.plan_id,
            expires_at: plan.expires_at,
            affected_count: blocks.length,
            sample_diffs: sampleDiffs,
            message: 'CMS block update plan created. Call cms.commit_bulk_update_blocks to execute.',
          };
        },
      },
    
      // ── Commit Bulk Update Blocks ─────────────────────────────────────────
      {
        name: 'cms.commit_bulk_update_blocks',
        description: 'Execute a previously prepared CMS block bulk update.',
        riskTier: RiskTier.Risk,
        requiresAuth: true,
        handler: async (params: Record<string, unknown>, context: ActionContext) => {
          const validated = CmsCommitBulkUpdateBlocksSchema.parse(params);
          guardrails.requireConfirmation(RiskTier.Risk, params);
    
          const plan = planStore.consume(validated.plan_id);
          if (!plan) {
            throw new Error('Plan not found or expired.');
          }
    
          const payload = plan.payload as {
            block_ids: number[];
            block_identifiers?: Record<number, string>;
            updates: Record<string, unknown>;
            scope?: { store_view_code?: string };
          };
          const client = context.getClient();
          const storeCode = payload.scope?.store_view_code;
    
          let successCount = 0;
          const errors: Array<{ block_id: number; error: string }> = [];
    
          for (const blockId of payload.block_ids) {
            try {
              const identifier = payload.block_identifiers?.[blockId];
              const blockPayload: Record<string, unknown> = { id: blockId, ...payload.updates };
              if (identifier) {
                blockPayload.identifier = identifier;
              }
              await client.put(`/V1/cmsBlock/${blockId}`, {
                block: blockPayload,
              }, storeCode);
              successCount++;
            } catch (err) {
              errors.push({ block_id: blockId, error: err instanceof Error ? err.message : String(err) });
            }
          }
    
          return {
            message: `Updated ${successCount}/${payload.block_ids.length} CMS blocks.`,
            success_count: successCount,
            error_count: errors.length,
            errors: errors.length > 0 ? errors : undefined,
          };
        },
      },
    ];
Behavior2/5

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

No annotations are provided, so the description carries the full burden of disclosing behavioral traits. The description only states it 'gets' a block, implying a read-only operation, but does not mention side effects, authentication requirements, rate limits, or any error conditions. This is insufficient for a tool with no annotation safety net.

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

Conciseness3/5

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

The description is concise at one sentence, which is positive. However, it lacks structure; there is no front-loading of key information beyond the basic action. While every word is necessary, the description could be expanded to include more context without sacrificing brevity.

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

Completeness2/5

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

Given no annotations, no output schema, and a vague input schema, the description is incomplete. It does not explain what a CMS block is, what the return value looks like, or any prerequisites for using this tool. An agent would need to rely on additional context or trial and error.

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

Parameters2/5

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

The input schema has 100% description coverage, but the description is generic ('Action parameters as a JSON object') and does not specify the expected keys. The tool description adds that it gets by ID, but does not clarify where the ID goes or its format. The schema itself lacks parameter-level descriptions for the 'params' object properties, and the description does not compensate.

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

Purpose4/5

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

The description 'Get a CMS block by ID' clearly states the action (get), resource (CMS block), and method (by ID). It directly indicates what the tool does. However, it does not distinguish this tool from sibling tools like cms_get_page or cms_search_blocks, which could also retrieve blocks, reducing differentiation.

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

Usage Guidelines2/5

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

No usage guidelines are provided. The description does not specify when to use this tool versus alternatives like cms_search_blocks or cms_get_page, nor does it mention any prerequisites or limitations. The agent must infer usage from the tool name alone.

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/thomastx05/magento-mcp'

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