Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(mcp-host): look up names the model sends only among a table's own entries

marcoteb7ba936781fce
diff --git a/mcp-host/src/workflow/__tests__/internalTools.prototypeKeys.test.ts b/mcp-host/src/workflow/__tests__/internalTools.prototypeKeys.test.ts
new file mode 100644
index 000000000..7390b4f11
--- /dev/null
+++ b/mcp-host/src/workflow/__tests__/internalTools.prototypeKeys.test.ts
@@ -0,0 +1,99 @@
+/**
+ * Names a model sends are looked up in fixed tables: colours, number formats,
+ * palettes, themes, block types. A name such as "constructor" or "toString" is
+ * also a key every object inherits, so each table must answer only for its own
+ * entries, or a function lands where a colour or a palette was expected.
+ */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+import { INTERNAL_TOOLS } from '../internalTools'
+import { zipEntryText } from './support/zipEntries'
+
+const tool = (name: string) => INTERNAL_TOOLS.find(t => t.name === `clerum__generate_${name}`)!
+const LEAKED = /native code|\[object Object\]|function Object\(\)/
+
+let dir: string
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-prototype-keys-'))
+})
+afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true })
+})
+
+describe('names that every object inherits', () => {
+ it.each(['constructor', 'toString', '__proto__'])(
+ 'xlsx reads %s as no colour, format or palette',
+ async word => {
+ const result = await tool('xlsx').execute(
+ {
+ filename: 'p.xlsx',
+ palette: word,
+ sheets: [
+ {
+ name: 'S',
+ rows: [['Amount'], [1], [2]],
+ titleRow: { text: 'T', fillColor: word, fontColor: word },
+ columnFormats: { Amount: word },
+ conditionalFormatting: [
+ { column: 'Amount', rules: [{ equals: 1, fillColor: word, fontColor: word }] },
+ ],
+ },
+ ],
+ },
+ dir
+ )
+ expect(result.success, result.error).toBe(true)
+ const styles = await zipEntryText(result.artifact!.path, 'xl/styles.xml')
+ expect(styles).not.toMatch(LEAKED)
+ }
+ )
+
+ it.each([
+ ['pdf', { body: 'Text.' }],
+ ['docx', { body: 'Text.' }],
+ ['pptx', { slides: [{ layout: 'title-bullets', title: 'T', bullets: ['a'] }] }],
+ ])('%s takes an inherited palette name as an unknown one', async (name, args) => {
+ for (const word of ['constructor', 'toString', '__proto__']) {
+ const result = await tool(name).execute(
+ { filename: `p.${name}`, palette: word, ...args },
+ dir
+ )
+ expect(result.success, `${word}: ${result.error}`).toBe(true)
+ }
+ })
+
+ it('draws a chart whose theme is an inherited name with a known theme', async () => {
+ for (const theme of ['constructor', 'toString', '__proto__']) {
+ const result = await tool('chart').execute(
+ {
+ filename: 'c.png',
+ chartType: 'bar',
+ theme,
+ data: { labels: ['a'], datasets: [{ label: 'x', data: [1] }] },
+ },
+ dir
+ )
+ expect(result.success, `${theme}: ${result.error}`).toBe(true)
+ }
+ })
+
+ it('reports a dashboard block whose type is an inherited name as unknown', async () => {
+ const result = await tool('dashboard').execute(
+ {
+ filename: 'd.html',
+ template: 'custom',
+ data: {
+ title: 'T',
+ blocks: [{ type: 'constructor' }, { type: 'kpis', items: [{ label: 'A', value: '1' }] }],
+ },
+ },
+ dir
+ )
+ expect(result.success, result.error).toBe(true)
+ const html = fs.readFileSync(result.artifact!.path, 'utf8')
+ expect(html).not.toMatch(LEAKED)
+ expect(result.content).toContain('data.blocks[0].type "constructor" is not a block type')
+ })
+})
diff --git a/mcp-host/src/workflow/chartGenerator.ts b/mcp-host/src/workflow/chartGenerator.ts
index 6ae623705..a83bfdbe1 100644
--- a/mcp-host/src/workflow/chartGenerator.ts
+++ b/mcp-host/src/workflow/chartGenerator.ts
@@ -40,6 +40,7 @@ import {
} from './chartThemes'
import { PNG_BASE_PPM } from './embeddedImages'
import { CHART_FONT_STACK, ensureFontsReady, sanitizeForFont } from './fonts'
+import { own } from './ownEntry'
import type { InternalToolResult } from './types'
// Register Chart.js controllers/scales/elements/plugins once. Chart.js v4 ships
@@ -657,7 +658,7 @@ export async function runGenerateChart(
}
}
const themeName = String(args.theme ?? 'light')
- const theme = CHART_THEMES[themeName] ?? CHART_THEMES.light
+ const theme = own(CHART_THEMES, themeName) ?? CHART_THEMES.light
const title = args.title ? sanitizeForFont(String(args.title)) : undefined
const yAxisLabel = args.yAxisLabel ? sanitizeForFont(String(args.yAxisLabel)) : undefined
diff --git a/mcp-host/src/workflow/dashboardRender.ts b/mcp-host/src/workflow/dashboardRender.ts
index 216fc73f9..7d440c254 100644
--- a/mcp-host/src/workflow/dashboardRender.ts
+++ b/mcp-host/src/workflow/dashboardRender.ts
@@ -19,6 +19,7 @@ import {
type DashboardThemeColors,
type ThemeName,
} from './dashboardThemes'
+import { own } from './ownEntry'
import { headerText, normalizeTableRows } from './tableRows'
import type { InternalToolResult } from './types'
@@ -1175,8 +1176,7 @@ const SERVICE_STATUSES = ['healthy', 'degraded', 'down', 'maintenance'] as const
/** Status words models use, by the card color they mean. */
/** The entry `words` has for `text`, ignoring case; never one inherited from Object. */
function ownWord<T>(words: Partial<Record<string, T>>, text: string): T | undefined {
- const key = text.toLowerCase()
- return Object.hasOwn(words, key) ? words[key] : undefined
+ return own(words, text.toLowerCase())
}
const SERVICE_STATUS_WORDS: Partial<Record<string, (typeof SERVICE_STATUSES)[number]>> = {
@@ -1543,7 +1543,7 @@ const BLOCK_LISTS: Record<string, { field: 'items' | 'services'; alias: string;
/** Whether `block` gives its list under the other name only. */
function listUnderAlias(block: Record<string, unknown>): boolean {
- const list = BLOCK_LISTS[String(block.type)]
+ const list = own(BLOCK_LISTS, String(block.type))
return !!list && isEmptyList(block[list.field]) && !isEmptyList(block[list.alias])
}
@@ -1557,7 +1557,7 @@ function blockList(
where: string,
ctx: DashRender
): { value: unknown; at: string } {
- const { field, alias, noun } = BLOCK_LISTS[String(block.type)]
+ const { field, alias, noun } = own(BLOCK_LISTS, String(block.type))!
if (listUnderAlias(block)) {
ctx.warnings.push(`${where}: the list was read from ${alias}; name it ${field}.`)
return { value: block[alias], at: `${where}.${alias}` }
diff --git a/mcp-host/src/workflow/docxGenerator.ts b/mcp-host/src/workflow/docxGenerator.ts
index ccba0cad9..be6493b60 100644
--- a/mcp-host/src/workflow/docxGenerator.ts
+++ b/mcp-host/src/workflow/docxGenerator.ts
@@ -43,6 +43,7 @@ import {
} from './docxStyle'
import { buildDocxTable, docxSections } from './docxTable'
import { htmlToPlainText } from './inlineMarkup'
+import { own } from './ownEntry'
import { normalizeTableRows } from './tableRows'
import type { InternalToolResult } from './types'
@@ -86,7 +87,7 @@ export async function runGenerateDocx(
const title = args.title ? htmlToPlainText(String(args.title)) : undefined
const headline = args.headline ? htmlToPlainText(String(args.headline)) : undefined
const body = String(args.body ?? '')
- const palette = DOCX_PALETTES[String(args.palette ?? 'default')] ?? DOCX_PALETTES.default
+ const palette = own(DOCX_PALETTES, String(args.palette ?? 'default')) ?? DOCX_PALETTES.default
const branding: DocxBranding = printedBranding(args.branding)
const images: unknown[] = Array.isArray(args.images) ? args.images : []
const tables: unknown[] = Array.isArray(args.tables) ? args.tables : []
diff --git a/mcp-host/src/workflow/embeddedImages.ts b/mcp-host/src/workflow/embeddedImages.ts
index d098cbcf6..86471dcdb 100644
--- a/mcp-host/src/workflow/embeddedImages.ts
+++ b/mcp-host/src/workflow/embeddedImages.ts
@@ -6,6 +6,7 @@ import { spawn } from 'child_process'
import * as fs from 'fs'
import * as path from 'path'
import { imageTarget } from './inlineMarkup'
+import { own } from './ownEntry'
export interface ImageSize {
width: number
@@ -327,7 +328,7 @@ function svgLength(tag: string, name: string): number | null | undefined {
if (!attr) return undefined
const m = new RegExp(`^\\s*(${SVG_NUMBER})\\s*([a-z%]*)\\s*$`, 'i').exec(attr[1])
if (m?.[2] === '%') return undefined
- const factor = m ? SVG_UNIT_PX[m[2].toLowerCase()] : undefined
+ const factor = m ? own(SVG_UNIT_PX, m[2].toLowerCase()) : undefined
return m && factor ? Number(m[1]) * factor : null
}
diff --git a/mcp-host/src/workflow/ownEntry.ts b/mcp-host/src/workflow/ownEntry.ts
new file mode 100644
index 000000000..09ded6b71
--- /dev/null
+++ b/mcp-host/src/workflow/ownEntry.ts
@@ -0,0 +1,10 @@
+/**
+ * Lookups in fixed tables keyed by text the model sends. A plain object also
+ * answers for the keys it inherits ("constructor", "toString", "__proto__"),
+ * which would hand a function or a prototype to code expecting an entry.
+ */
+
+/** The entry `table` has for `key` itself, or undefined. */
+export function own<T>(table: Partial<Record<string, T>>, key: string): T | undefined {
+ return Object.hasOwn(table, key) ? table[key] : undefined
+}
diff --git a/mcp-host/src/workflow/pdfGenerator.ts b/mcp-host/src/workflow/pdfGenerator.ts
index 211669dda..1aa37c091 100644
--- a/mcp-host/src/workflow/pdfGenerator.ts
+++ b/mcp-host/src/workflow/pdfGenerator.ts
@@ -39,6 +39,7 @@ import {
startsTable,
stripListMarker,
} from './markdownBlocks'
+import { own } from './ownEntry'
import {
BODY_FONT_SIZE,
MIN_BOTTOM_MARGIN,
@@ -850,7 +851,7 @@ export async function runGeneratePdf(
const title = args.title ? htmlToPlainText(String(args.title)) || undefined : undefined
const body = String(args.body ?? '')
const paletteName = String(args.palette ?? 'default')
- const palette = PDF_PALETTES[paletteName] ?? PDF_PALETTES.default
+ const palette = own(PDF_PALETTES, paletteName) ?? PDF_PALETTES.default
const branding: PdfBranding = printedBranding(args.branding)
const imageRefs = Array.isArray(args.images) ? args.images : []
const tables = (Array.isArray(args.tables) ? args.tables : []) as PdfTableSpec[]
diff --git a/mcp-host/src/workflow/pptxDeck.ts b/mcp-host/src/workflow/pptxDeck.ts
index 084c9aaf9..882dfd7b5 100644
--- a/mcp-host/src/workflow/pptxDeck.ts
+++ b/mcp-host/src/workflow/pptxDeck.ts
@@ -9,6 +9,7 @@
import JSZip from 'jszip'
import { bidiLanguage, documentEastAsianScript, isRtlText, scriptSegments } from './docxScript'
import { fitImageSize } from './embeddedImages'
+import { own } from './ownEntry'
import { nativeChartArgs } from './pptxCharts'
import {
type PptxColumn,
@@ -1231,7 +1232,8 @@ function pick<T>(
warnings: string[]
): T {
if (value === undefined || value === null || value === '') return table[fallback]
- if (typeof value === 'string' && table[value]) return table[value]
+ const entry = typeof value === 'string' ? own(table, value) : undefined
+ if (entry) return entry
warnings.push(
`${field} ${JSON.stringify(value)} is not one of ${Object.keys(table).join(', ')}; ` +
`"${fallback}" was used.`
diff --git a/mcp-host/src/workflow/xlsxFormats.ts b/mcp-host/src/workflow/xlsxFormats.ts
index 0da99411e..9030489da 100644
--- a/mcp-host/src/workflow/xlsxFormats.ts
+++ b/mcp-host/src/workflow/xlsxFormats.ts
@@ -2,6 +2,7 @@
* Number formats for XLSX columns: the keywords a caller may ask for, and the
* format a column gets from its header and values when nobody asked.
*/
+import { own } from './ownEntry'
import { CURRENCY_SYMBOLS } from './xlsxCells'
export const NUMBER_FORMATS = {
@@ -98,7 +99,8 @@ export function formatSpec(value: unknown): FormatSpec | undefined {
.trim()
.toLowerCase()
.replace(/[\s_-]+/g, '')
- if (KEYWORDS[key]) return KEYWORDS[key]
+ const keyword = own(KEYWORDS, key)
+ if (keyword) return keyword
const code = /^(?:currency|money)[:(]?([a-z]{3})\)?$/.exec(key)?.[1] ?? key
if (/^[a-z]{3}$/.test(code)) {
const upper = code.toUpperCase()
diff --git a/mcp-host/src/workflow/xlsxSheet.ts b/mcp-host/src/workflow/xlsxSheet.ts
index eb4aa2cc5..c6f6e63c5 100644
--- a/mcp-host/src/workflow/xlsxSheet.ts
+++ b/mcp-host/src/workflow/xlsxSheet.ts
@@ -2,6 +2,7 @@
* The shape of an XLSX sheet request: its rows, its name, the columns other
* arguments point at, and the colors it names.
*/
+import { own } from './ownEntry'
import { headerText, normalizeTableRows } from './tableRows'
import { cellProblem } from './xlsxCells'
@@ -210,7 +211,7 @@ export function parseColor(input: unknown): string | undefined {
.map(v => Number(v).toString(16).padStart(2, '0'))
.join('')}`.toUpperCase()
}
- const named = NAMED_COLORS[text.toLowerCase().replace(/[\s_-]+/g, '')]
+ const named = own(NAMED_COLORS, text.toLowerCase().replace(/[\s_-]+/g, ''))
return named ? `FF${named}` : undefined
}
diff --git a/mcp-host/src/workflow/xlsxWorkbook.ts b/mcp-host/src/workflow/xlsxWorkbook.ts
index c17315c8a..4c1d4823c 100644
--- a/mcp-host/src/workflow/xlsxWorkbook.ts
+++ b/mcp-host/src/workflow/xlsxWorkbook.ts
@@ -10,6 +10,7 @@ import {
fitImageSize,
loadEmbeddableImage,
} from './embeddedImages'
+import { own } from './ownEntry'
import { headerText } from './tableRows'
import {
type SheetCell,
@@ -897,7 +898,7 @@ export async function buildXlsxWorkbook(
'images belongs inside each sheet (sheets[i].images); the top-level images were placed on the first sheet.'
)
}
- const palette = XLSX_PALETTES[String(args.palette ?? 'default')] ?? XLSX_PALETTES.default
+ const palette = own(XLSX_PALETTES, String(args.palette ?? 'default')) ?? XLSX_PALETTES.default
const branding = isRecord(args.branding) ? args.branding : {}
const company = typeof branding.companyName === 'string' ? branding.companyName : ''