Skip to main content
Glama

Data Table

render_table
Read-onlyIdempotent

Render a sortable, interactive data table with customizable themes for styled visuals.

Instructions

Render a sortable, interactive data table. Click column headers to sort. Supports themes for styled visuals.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
titleYesTable title
columnsYesColumn names in display order
rowsYesArray of row objects. Keys must match column names.
optionsNo
themeNoTheme preset: boardroom, corporate, sales-floor, golden-treasury, clinical, startup, ops-control, tokyo-midnight, zen-garden, consultant, black-tron, black-elegance, black-matrix, forest-amber, forest-earth, sky-light, sky-ocean, sky-twilight, gray-hf, gray-copilot
paletteNoOverride palette only (mix-and-match)
typographyNoOverride typography: professional, luxury, cyberpunk, editorial, mono, bold, system, techno
effectsNoOverride effects: none, subtle, shimmer, neon, energetic

Implementation Reference

  • Main handler function for the render_table tool. Takes a container HTMLElement and TableData payload, builds an HTML table with striped rows, column sorting via click, row-click selection messaging, and CSV export button. Injects styles, applies themes, and renders title/subtitle metadata.
    export function renderTable(container: HTMLElement, payload: TableData): void {
      const { title, columns, rows, options = {} } = payload;
      const sortable = options.sortable !== false; // default true
      const striped = options.striped === true;
    
      // Apply theme if specified
      const theme = resolveTheme(payload.theme, {
        palette: payload.palette,
        typography: payload.typography,
        effects: payload.effects,
      });
      if (theme) applyTheme(container, theme);
    
      injectStyles(container);
    
      const rowCount = rows.length;
      const colCount = columns.length;
      const subtitle =
        `${rowCount} row${rowCount !== 1 ? "s" : ""} \u00b7 ${colCount} column${colCount !== 1 ? "s" : ""}`;
    
      const numericCols = detectNumericColumns(columns, rows);
    
      // Build header cells
      const headerCells = columns
        .map((col, i) => {
          const align = numericCols.has(col) ? "right" : "left";
          const sortClass = sortable ? " tbl-sortable" : "";
          const icon = sortable
            ? `<span class="tbl-sort-icon" data-icon="${i}">▴▾</span>`
            : "";
          return `<th class="tbl-th${sortClass}" data-col="${i}" style="text-align:${align}" title="${escapeHtml(col)}">${escapeHtml(col)}${icon}</th>`;
        })
        .join("");
    
      // Build body rows
      let bodyHtml = "";
      if (rows.length === 0) {
        bodyHtml = `<tr><td class="tbl-empty" colspan="${columns.length}">No data</td></tr>`;
      } else {
        for (let ri = 0; ri < rows.length; ri++) {
          const row = rows[ri];
          const cells = columns
            .map((col) => {
              const val = row[col];
              const cellClass = numericCols.has(col) ? "tbl-num" : "tbl-str";
              const display = escapeHtml(formatCell(val));
              return `<td class="${cellClass}">${display}</td>`;
            })
            .join("");
          bodyHtml += `<tr data-row-idx="${ri}">${cells}</tr>`;
        }
      }
    
      const stripedClass = striped ? " tbl--striped" : "";
    
      container.innerHTML = `
        <div class="chart-view">
          <div class="card chart-card">
            <div class="chart-card__header">
              <div>
                <div class="chart-card__title${theme?.effects.shimmerTitle ? " shimmer-text" : ""}">${escapeHtml(title)}</div>
                <div class="chart-card__subtitle tbl-meta">${subtitle}</div>
              </div>
            </div>
            <div class="chart-card__body" style="display:flex;flex-direction:column;">
              <div class="tbl-wrap">
                <table class="tbl${stripedClass}">
                  <thead>
                    <tr>${headerCells}</tr>
                  </thead>
                  <tbody id="tbl-body">
                    ${bodyHtml}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      `;
    
      // Re-inject the style tag (innerHTML wipe removed it)
      injectStyles(container);
    
      // CSV export button
      const card = container.querySelector<HTMLElement>(".chart-card");
      if (card) addCsvExportButton(card, columns, rows, title);
    
      // Row click events for bidirectional messaging
      const tbody = container.querySelector<HTMLElement>("#tbl-body")!;
      tbody.addEventListener("click", (e) => {
        const tr = (e.target as HTMLElement).closest<HTMLElement>("tr[data-row-idx]");
        if (!tr) return;
        const idx = parseInt(tr.dataset.rowIdx ?? "0", 10);
        const row = rows[idx];
        if (!row) return;
        const summary = columns.map((col) => `${col}: ${row[col] ?? ""}`).join(", ");
        sendClickMessage(`Row ${idx + 1} in "${title}": ${summary}`);
      });
    
      if (!sortable || rows.length === 0) return;
    
      // Sorting state
      let sortCol: number | null = null;
      let sortAsc = true;
    
      // Working copy of rows - indices into original rows array
      let sortedIndices: number[] = rows.map((_, i) => i);
    
      const headers = container.querySelectorAll<HTMLElement>(".tbl-th.tbl-sortable");
    
      function rebuildBody(): void {
        const colName = sortCol !== null ? columns[sortCol] : null;
        const isNum = colName !== null && numericCols.has(colName);
    
        const sorted = [...sortedIndices].sort((a, b) => {
          if (colName === null) return 0;
          const av = rows[a][colName];
          const bv = rows[b][colName];
    
          let cmp = 0;
          if (isNum) {
            const an = av === undefined || av === "" ? -Infinity : Number(av);
            const bn = bv === undefined || bv === "" ? -Infinity : Number(bv);
            cmp = an - bn;
          } else {
            const as = av === undefined ? "" : String(av);
            const bs = bv === undefined ? "" : String(bv);
            cmp = as.localeCompare(bs, undefined, { numeric: true, sensitivity: "base" });
          }
          return sortAsc ? cmp : -cmp;
        });
        sortedIndices = sorted;
    
        let html = "";
        for (const idx of sortedIndices) {
          const row = rows[idx];
          const cells = columns
            .map((col) => {
              const val = row[col];
              const cellClass = numericCols.has(col) ? "tbl-num" : "tbl-str";
              const display = escapeHtml(formatCell(val));
              return `<td class="${cellClass}">${display}</td>`;
            })
            .join("");
          html += `<tr data-row-idx="${idx}">${cells}</tr>`;
        }
        tbody.innerHTML = html;
      }
    
      headers.forEach((th) => {
        th.addEventListener("click", () => {
          const colIdx = parseInt(th.dataset.col ?? "0", 10);
    
          if (sortCol === colIdx) {
            sortAsc = !sortAsc;
          } else {
            sortCol = colIdx;
            sortAsc = true;
          }
    
          // Update header visuals
          headers.forEach((h) => {
            h.classList.remove("tbl-sorted");
            const icon = h.querySelector<HTMLElement>(".tbl-sort-icon");
            if (icon) icon.innerHTML = "▴▾";
          });
          th.classList.add("tbl-sorted");
          const activeIcon = th.querySelector<HTMLElement>(".tbl-sort-icon");
          if (activeIcon) {
            activeIcon.innerHTML = sortAsc ? "▴" : "▾";
          }
    
          rebuildBody();
        });
      });
    }
  • TableData interface defining the input schema for render_table: title (string), columns (string[]), rows (array of Record<string, string|number>), optional sortable/striped options, and theme/palette/typography/effects styling fields.
    export interface TableData {
      title: string;
      columns: string[];
      rows: Array<Record<string, string | number>>;
      options?: {
        sortable?: boolean;
        striped?: boolean;
      };
      theme?: string;
      palette?: string;
      typography?: string;
      effects?: string;
    }
  • Registration call: registerChart('table', 'render_table', renderTable) which maps the internal type 'table' to the tool name 'render_table' and the render function.
    registerChart("table", "render_table", renderTable);
  • toTableData helper function in auto.ts that converts arbitrary data into the TableData format expected by renderTable. Handles arrays of objects, plain objects (converts to two-column key-value table), and primitive arrays.
    function toTableData(title: string, data: any): Parameters<typeof renderTable>[1] {
      if (Array.isArray(data) && data.length > 0 && typeof data[0] === "object" && data[0] !== null) {
        const columns = Object.keys(data[0]);
        return { title, columns, rows: data };
      }
    
      // Object - convert to two-column table
      if (!Array.isArray(data) && typeof data === "object" && data !== null) {
        const flat = tryFlatten(data) as Record<string, any>;
        return {
          title,
          columns: ["Key", "Value"],
          rows: Object.entries(flat).map(([k, v]) => ({ Key: k, Value: String(v) })),
        };
      }
    
      return { title, columns: ["Value"], rows: (data as any[]).map((v) => ({ Value: String(v) })) };
    }
  • addCsvExportButton helper used by renderTable to add a CSV download button to the table card header.
    export function addCsvExportButton(
      container: HTMLElement,
      columns: string[],
      rows: Array<Record<string, string | number>>,
      filename: string
    ): void {
      const header = container.querySelector(".chart-card__header");
      if (!header) return;
    
      const btn = document.createElement("button");
      btn.className = "export-btn";
      btn.title = "Download as CSV";
      btn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>`;
      btn.addEventListener("click", () => {
        const csvRows = [columns.join(",")];
        for (const row of rows) {
          csvRows.push(columns.map((col) => {
            const val = String(row[col] ?? "");
            return val.includes(",") || val.includes('"') || val.includes("\n")
              ? `"${val.replace(/"/g, '""')}"`
              : val;
          }).join(","));
        }
        saveViaServer(`${filename}.csv`, csvRows.join("\n"), "utf-8");
      });
      getOrCreateActions(header).appendChild(btn);
    }
Behavior4/5

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

Annotations already declare readOnlyHint and idempotentHint. The description adds behavioral traits like interactive sorting and theme support, going beyond annotations. However, it does not detail all interactive behaviors or limitations.

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?

The description is two sentences, front-loading the purpose and adding one key behavioral detail. There is no fluff; every sentence adds value.

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?

No output schema exists, but the description is adequate for a simple table renderer. It misses details about customization parameters (options, theme, palette, etc.) that are present in the schema, which could be more explicitly referenced.

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 88% (high), so baseline is 3. The description does not add parameter-specific meaning beyond what the schema provides, but the high coverage makes this acceptable.

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 clearly states 'Render a sortable, interactive data table,' specifying verb and resource. It distinguishes from sibling chart tools by explicitly naming it a data table, not a chart. The mention of sorting and themes further clarifies its function.

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 implies usage for tabular data but does not explicitly state when to use this tool versus alternatives like charts or other renders. No exclusions or context about when not to use it are provided.

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/KyuRish/mcp-dashboards'

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