Skip to main content
Glama

align_elements

Align multiple diagram elements horizontally or vertically to create organized layouts in Excalidraw diagrams.

Instructions

Align elements (left, center, right, top, middle, bottom)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
elementIdsYes
alignmentYes

Implementation Reference

  • The main handler function alignElementsTool that implements the align_elements tool logic. It parses input args, fetches elements, and performs alignment operations (left, center, right, top, middle, bottom) by updating element coordinates.
    export async function alignElementsTool(
      args: unknown,
      client: CanvasClient
    ) {
      const { elementIds, alignment } = AlignElementsSchema.parse(args);
    
      const elements = await Promise.all(
        elementIds.map(async (id) => {
          const el = await client.getElement(id);
          if (!el) throw new Error(`Element ${id} not found`);
          return el;
        })
      );
    
      switch (alignment) {
        case 'left': {
          const minX = Math.min(...elements.map((el) => el.x));
          for (const el of elements) {
            if (el.x !== minX) {
              await client.updateElement(el.id, { x: minX });
            }
          }
          break;
        }
        case 'right': {
          const maxRight = Math.max(
            ...elements.map((el) => el.x + (el.width ?? 0))
          );
          for (const el of elements) {
            const newX = maxRight - (el.width ?? 0);
            if (el.x !== newX) {
              await client.updateElement(el.id, { x: newX });
            }
          }
          break;
        }
        case 'center': {
          const avgCenterX =
            elements.reduce((sum, el) => sum + el.x + (el.width ?? 0) / 2, 0) /
            elements.length;
          for (const el of elements) {
            const newX = avgCenterX - (el.width ?? 0) / 2;
            if (el.x !== newX) {
              await client.updateElement(el.id, { x: newX });
            }
          }
          break;
        }
        case 'top': {
          const minY = Math.min(...elements.map((el) => el.y));
          for (const el of elements) {
            if (el.y !== minY) {
              await client.updateElement(el.id, { y: minY });
            }
          }
          break;
        }
        case 'bottom': {
          const maxBottom = Math.max(
            ...elements.map((el) => el.y + (el.height ?? 0))
          );
          for (const el of elements) {
            const newY = maxBottom - (el.height ?? 0);
            if (el.y !== newY) {
              await client.updateElement(el.id, { y: newY });
            }
          }
          break;
        }
        case 'middle': {
          const avgCenterY =
            elements.reduce((sum, el) => sum + el.y + (el.height ?? 0) / 2, 0) /
            elements.length;
          for (const el of elements) {
            const newY = avgCenterY - (el.height ?? 0) / 2;
            if (el.y !== newY) {
              await client.updateElement(el.id, { y: newY });
            }
          }
          break;
        }
      }
    
      return { success: true, aligned: true, alignment, elementIds };
    }
  • Zod schema definition for AlignElements input validation, specifying elementIds array (min 2, max) and alignment enum values.
    export const AlignElementsSchema = z
      .object({
        elementIds: z
          .array(z.string().max(LIMITS.MAX_ID_LENGTH))
          .min(2)
          .max(LIMITS.MAX_ELEMENT_IDS),
        alignment: z.enum([
          'left',
          'center',
          'right',
          'top',
          'middle',
          'bottom',
        ]),
      })
      .strict();
  • Type inference for AlignElements from the schema, enabling TypeScript type checking.
    export type AlignElements = z.infer<typeof AlignElementsSchema>;
  • MCP server tool registration for align_elements with inline handler implementation, including input schema validation and the alignment logic.
    // --- Tool: align_elements ---
    server.tool(
      'align_elements',
      'Align elements (left, center, right, top, middle, bottom)',
      {
        elementIds: z.array(IdZ).min(2).max(LIMITS.MAX_ELEMENT_IDS),
        alignment: z.enum(['left', 'center', 'right', 'top', 'middle', 'bottom']),
      },
      async ({ elementIds, alignment }) => {
        try {
          const elements = [];
          for (const eid of elementIds) {
            const el = await client.getElement(eid);
            if (!el) throw new Error(`Element ${eid} not found`);
            if (el.locked) throw new Error(`Element ${eid} is locked`);
            elements.push(el);
          }
    
          switch (alignment) {
            case 'left': {
              const minX = Math.min(...elements.map(e => e.x));
              for (const el of elements) await client.updateElement(el.id, { x: minX });
              break;
            }
            case 'right': {
              const maxRight = Math.max(...elements.map(e => e.x + (e.width ?? 0)));
              for (const el of elements) await client.updateElement(el.id, { x: maxRight - (el.width ?? 0) });
              break;
            }
            case 'center': {
              const centers = elements.map(e => e.x + (e.width ?? 0) / 2);
              const avg = centers.reduce((a, b) => a + b, 0) / centers.length;
              for (const el of elements) await client.updateElement(el.id, { x: avg - (el.width ?? 0) / 2 });
              break;
            }
            case 'top': {
              const minY = Math.min(...elements.map(e => e.y));
              for (const el of elements) await client.updateElement(el.id, { y: minY });
              break;
            }
            case 'bottom': {
              const maxBottom = Math.max(...elements.map(e => e.y + (e.height ?? 0)));
              for (const el of elements) await client.updateElement(el.id, { y: maxBottom - (el.height ?? 0) });
              break;
            }
            case 'middle': {
              const middles = elements.map(e => e.y + (e.height ?? 0) / 2);
              const avgY = middles.reduce((a, b) => a + b, 0) / middles.length;
              for (const el of elements) await client.updateElement(el.id, { y: avgY - (el.height ?? 0) / 2 });
              break;
            }
          }
    
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({ aligned: true, alignment, elementIds }, null, 2),
            }],
          };
        } catch (err) {
          return { content: [{ type: 'text', text: `Error: ${(err as Error).message}` }], isError: true };
        }
      }
    );
  • Export statement that makes the alignElementsTool handler available to other modules.
    export { alignElementsTool } from './align-elements.js';
Behavior2/5

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

With no annotations, the description carries full burden but only states the action without behavioral details. It doesn't disclose if this is a mutation (likely yes), what permissions are needed, whether it's reversible, or any side effects (e.g., changes element positions). The description adds minimal context beyond the basic function.

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?

Extremely concise and front-loaded: a single phrase that directly states the tool's function and key parameter options. Every word earns its place with no redundancy or fluff.

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?

For a mutation tool with no annotations and no output schema, the description is incomplete. It lacks details on what 'elements' are, the effect of alignment (e.g., relative to what), error conditions, or return values. Given the context of sibling tools like 'lock_elements', more guidance on interactions would be helpful.

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

Parameters4/5

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

Schema description coverage is 0%, but the description compensates by explaining the 'alignment' parameter with its enum values (left, center, right, top, middle, bottom). It doesn't explain 'elementIds' (e.g., what they are, format), but with only 2 parameters and one well-documented, it adds significant value over the bare schema.

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

Purpose3/5

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

The description states the action ('align') and the resource ('elements'), but it's vague about what elements are (likely UI/diagram elements) and doesn't distinguish from siblings like 'distribute_elements' or 'group_elements'. It specifies alignment options but lacks context about the domain.

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 guidance on when to use this tool versus alternatives like 'distribute_elements' or 'group_elements'. It implies usage for aligning multiple elements but doesn't mention prerequisites (e.g., elements must exist) or exclusions (e.g., cannot align locked elements).

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/debu-sinha/excalidraw-mcp-server'

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