@cyanheads/calculator-mcp-server 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,7 @@
6
6
  import { tool, z } from '@cyanheads/mcp-ts-core';
7
7
  import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
8
8
  import { getMathService } from '../../../services/math/math-service.js';
9
+ import { MAX_EVALUATION_ELEMENTS, MAX_MATRIX_ELEMENTS } from '../../../services/math/size-guard.js';
9
10
  export const calculateTool = tool('calculate', {
10
11
  description: 'Evaluate math expressions, simplify algebraic expressions, or compute symbolic derivatives. One expression per call. Supports arithmetic, trigonometry, statistics, matrices, complex numbers, units, and combinatorics.',
11
12
  annotations: {
@@ -17,7 +18,7 @@ export const calculateTool = tool('calculate', {
17
18
  expression: z
18
19
  .string()
19
20
  .min(1)
20
- .describe(`One mathematical expression per call — neither \`;\` nor newlines separate statements. Inside matrices, \`;\` separates rows (e.g. \`[1, 2; 3, 4]\`). Supports arithmetic (+, -, *, /, ^, %), functions across arithmetic/trig (sin, cos, sqrt, log, abs, round), statistics (mean, median, std, variance), combinatorics (factorial, permutations, combinations), and matrix (det, inv, transpose), plus constants (pi, e, phi, i), units (5 kg to lbs), and variables (when scope is provided). Standard notation \`ln\` and \`arc*\` (e.g. \`arcsin\`, \`arctan\`) is accepted alongside the math.js names \`log\` and \`asin\`/\`atan\`; common synonyms such as \`stdev\`, \`permute\`, \`nCr\`, and \`length\`/\`len\` resolve to their math.js names (\`std\`, \`permutations\`, \`combinations\`, \`count\`).`),
21
+ .describe(`One mathematical expression per call — neither \`;\` nor newlines separate statements. Inside matrices, \`;\` separates rows (e.g. \`[1, 2; 3, 4]\`). Supports arithmetic (+, -, *, /, ^, %), functions across arithmetic/trig (sin, cos, sqrt, log, abs, round), statistics (mean, median, std, variance — std and variance return the sample (n − 1) form by default; pass "uncorrected" for the population form, e.g. \`std([2, 4, 6], "uncorrected")\`), combinatorics (factorial, permutations, combinations), and matrix (det, inv, transpose), plus constants (pi, e, phi, i), units (5 kg to lbs), and variables (when scope is provided). Standard notation \`ln\` and \`arc*\` (e.g. \`arcsin\`, \`arctan\`) is accepted alongside the math.js names \`log\` and \`asin\`/\`atan\`; common synonyms such as \`stdev\`, \`permute\`, \`nCr\`, and \`length\`/\`len\` resolve to their math.js names (\`std\`, \`permutations\`, \`combinations\`, \`count\`).`),
21
22
  operation: z
22
23
  .enum(['evaluate', 'simplify', 'derivative'])
23
24
  .default('evaluate')
@@ -36,24 +37,24 @@ export const calculateTool = tool('calculate', {
36
37
  scope: z
37
38
  .record(z.string(), z.number())
38
39
  .optional()
39
- .describe('Variable assignments for the expression. Example: { "x": 5, "y": 3 } makes "x + y" evaluate to 8.'),
40
+ .describe('Variable assignments for evaluate; simplify and derivative ignore them. Example: { "x": 5, "y": 3 } makes "x + y" evaluate to 8.'),
40
41
  precision: z
41
42
  .union([
42
43
  z.literal('').describe('Empty string — treated as omitted.'),
43
44
  z.number().int().min(1).max(16).describe('Significant digits (integer, 1–16).'),
44
45
  ])
45
46
  .optional()
46
- .describe('Significant digits (1–16) for numeric results. Omit for full precision. Empty string is treated as omitted. Ignored for symbolic operations (simplify, derivative).'),
47
+ .describe('Significant digits (1–16) for numeric results. Omit for full precision. Empty string is treated as omitted. Fraction results always print exactly, and symbolic operations (simplify, derivative) ignore it.'),
47
48
  numericType: z
48
49
  .enum(['number', 'BigNumber', 'Fraction'])
49
50
  .default('number')
50
- .describe('Numeric type for evaluate. "number" (default): 64-bit IEEE 754 float — fastest, standard precision. "BigNumber": arbitrary-precision decimal — use when intermediate values overflow 64-bit float (e.g. large factorial ratios like 10000!/9999!); slower than "number". "Fraction": exact rational arithmetic — eliminates floating-point rounding (e.g. 0.1 + 0.2 = 0.3 exactly); limited to expressions with exactly-rational results — an irrational or transcendental result (sqrt, sin, log, …) fails with fraction_unsupported, so use "number" or "BigNumber" for those. Ignored for symbolic operations (simplify, derivative). When "number" evaluation produces a non-finite result (undefined_result error), retry with "BigNumber".'),
51
+ .describe('Numeric type for evaluate. "number" (default): 64-bit IEEE 754 float — fastest, about 16 significant digits; a value past about 1.8e308 (171!, 2^1024, exp(1000)) overflows and fails with undefined_result. "BigNumber": decimal with 64 significant digits and a much wider exponent range, slower than "number" — retry an overflow with it; results are 64-digit approximations (10000!/9999! returns 9999.99…96, which precision: 16 rounds to 10000). Division by zero, 0/0, and log(0) are undefined in every numeric type, so another numeric type does not fix them. "Fraction": exact rational arithmetic (0.1 + 0.2 returns 3/10); fails with fraction_unsupported when the result has no exact rational value (sqrt(2), sin(1), log(3)), the expression calls a function Fraction mode cannot compute (sqrt(4), 5!, combinations(5, 2)), or it uses a value Fraction mode holds only as a rounded float (pi, e, 2^(1/2), a complex number with a non-integer part, number(x), random()) — use "number" or "BigNumber" for those. A unit conversion with an irrational factor (30 deg to rad) returns a close rational approximation, not an exact value. Ignored for symbolic operations (simplify, derivative).'),
51
52
  }),
52
53
  output: z.object({
53
54
  result: z.string().describe('The computed result as a string.'),
54
55
  resultType: z
55
56
  .string()
56
- .describe('Type of result as reported by math.js: number, BigNumber, Complex, DenseMatrix, Unit, string, boolean. Symbolic operations return "string".'),
57
+ .describe('Type of result as reported by math.js. Common values: number, BigNumber, Fraction, Complex, DenseMatrix, SparseMatrix, Array, Unit, string, boolean. Symbolic operations return "string".'),
57
58
  expression: z.string().describe('The original expression as received.'),
58
59
  operation: z
59
60
  .enum(['evaluate', 'simplify', 'derivative'])
@@ -61,11 +62,11 @@ export const calculateTool = tool('calculate', {
61
62
  scopeVars: z
62
63
  .array(z.string())
63
64
  .optional()
64
- .describe('Keys from the scope that were active during evaluation. Omitted when no scope was provided. Values are omitted to keep output compact.'),
65
+ .describe('Keys from the scope that were active during evaluation. Omitted when no scope was provided and for symbolic operations, which ignore scope. Values are omitted to keep output compact.'),
65
66
  precisionUsed: z
66
67
  .number()
67
68
  .optional()
68
- .describe('Significant-digit precision applied to the result. Omitted when full precision was used or the operation is symbolic.'),
69
+ .describe('The precision value supplied for evaluate. Fraction results print exactly regardless. Omitted when no precision was supplied or the operation is symbolic.'),
69
70
  unchanged: z
70
71
  .boolean()
71
72
  .optional()
@@ -75,56 +76,86 @@ export const calculateTool = tool('calculate', {
75
76
  {
76
77
  reason: 'empty_expression',
77
78
  code: JsonRpcErrorCode.ValidationError,
79
+ thrownBy: 'service',
78
80
  when: 'Expression is empty or whitespace-only.',
79
81
  recovery: 'Provide a non-empty math expression in the expression parameter.',
80
82
  },
81
83
  {
82
84
  reason: 'expression_too_long',
83
85
  code: JsonRpcErrorCode.ValidationError,
86
+ thrownBy: 'service',
84
87
  when: 'Expression exceeds the configured max length (CALC_MAX_EXPRESSION_LENGTH).',
85
88
  recovery: 'Shorten the expression or split it into multiple separate calls.',
86
89
  },
87
90
  {
88
91
  reason: 'multiple_expressions',
89
92
  code: JsonRpcErrorCode.ValidationError,
90
- when: 'Expression contains a separator (`;` or newline) outside matrix brackets.',
93
+ thrownBy: 'service',
94
+ when: 'Expression holds more than one statement — a `;` or newline at the top level, outside brackets, parentheses, and string literals.',
91
95
  recovery: 'Send one expression per call; issue separate calls for each statement.',
92
96
  },
93
97
  {
94
98
  reason: 'reserved_scope_key',
95
99
  code: JsonRpcErrorCode.ValidationError,
100
+ thrownBy: 'service',
96
101
  when: 'Scope contains a reserved JS property name (`__proto__`, `constructor`, etc.).',
97
102
  recovery: 'Rename the variable to avoid reserved JavaScript property names.',
98
103
  },
99
104
  {
100
105
  reason: 'disallowed_result_type',
101
106
  code: JsonRpcErrorCode.ValidationError,
102
- when: 'Result is a function, parser, or multi-expression ResultSet, or the expression converts a function to a string (e.g. `cos.toString()`) — security guard.',
103
- recovery: 'Rewrite the expression to produce a value (number, matrix, unit) instead of a function or its source.',
107
+ thrownBy: 'service',
108
+ when: 'The result is a function (e.g. a bare `sin`, or `f(x) = x^2`) or a help() object, or the expression converts a function to a string (e.g. `cos.toString()`) — security guard.',
109
+ recovery: 'Rewrite the expression to produce a value (number, matrix, unit) instead of a function or its source; for function documentation, read the calculator://help resource.',
104
110
  },
105
111
  {
106
112
  reason: 'result_too_large',
107
113
  code: JsonRpcErrorCode.ValidationError,
108
- when: 'Stringified result exceeds the configured max size (CALC_MAX_RESULT_LENGTH).',
114
+ thrownBy: 'service',
115
+ when: `The result exceeds the configured max size (CALC_MAX_RESULT_LENGTH), or the expression would build a matrix or string over the per-call limit (${MAX_MATRIX_ELEMENTS.toLocaleString('en-US')} elements or characters), or more than ${MAX_EVALUATION_ELEMENTS.toLocaleString('en-US')} in total across one evaluation.`,
109
116
  recovery: 'Reduce precision, narrow the input range, or compute smaller subproblems separately.',
110
117
  },
111
118
  {
112
119
  reason: 'undefined_result',
113
120
  code: JsonRpcErrorCode.ValidationError,
114
- when: 'Expression evaluated to Infinity, -Infinity, or NaN (e.g., division by zero).',
115
- recovery: 'Check for division by zero, log of non-positive numbers, or other undefined operations.',
121
+ thrownBy: 'service',
122
+ when: 'The result is Infinity, -Infinity, or NaN anywhere in it (including matrix elements, unit magnitudes, and object values): an undefined operation such as 1/0, 0/0, or log(0), or a value that overflowed its numeric range (e.g. 171! or 2^1024 under numericType "number").',
123
+ recovery: 'Division by zero, 0/0, and log(0) are undefined in every numericType, so fix the expression; for an overflow (large powers, factorials, exp), retry with numericType "BigNumber".',
116
124
  },
117
125
  {
118
126
  reason: 'fraction_unsupported',
119
127
  code: JsonRpcErrorCode.ValidationError,
120
- when: 'numericType is "Fraction" but the expression has no exact rational value (irrational or transcendental result, e.g. sqrt, sin, log).',
121
- recovery: 'Retry with numericType "number" or "BigNumber" — those represent irrational and transcendental results.',
128
+ thrownBy: 'service',
129
+ when: 'numericType is "Fraction" and the result has no exact rational value (e.g. sqrt(2), sin(1), log(3)), the expression calls a function Fraction mode cannot compute, even for a rational result (e.g. sqrt(4), 5!, combinations(5, 2)), or it uses a value Fraction mode holds only as a rounded 64-bit float (e.g. pi, e, 2^(1/2), a complex number with a non-integer part, number(x), random()).',
130
+ recovery: 'Retry with numericType "number" or "BigNumber" — both compute these functions and values, including irrational and transcendental results.',
122
131
  },
123
132
  {
124
133
  reason: 'parse_failed',
125
134
  code: JsonRpcErrorCode.ValidationError,
126
- when: 'mathjs could not parse the expression.',
127
- recovery: 'Check syntax for balanced parentheses, valid operators, and correct function names.',
135
+ thrownBy: 'service',
136
+ when: 'mathjs could not parse the expression, or it names an undefined symbol, function, or unit, or calls a function disabled for security.',
137
+ recovery: 'Check syntax for balanced parentheses, valid operators, and correct function and unit names; pass variable values through scope.',
138
+ },
139
+ {
140
+ reason: 'operation_as_function',
141
+ code: JsonRpcErrorCode.ValidationError,
142
+ thrownBy: 'service',
143
+ when: 'The expression calls `evaluate`, `simplify`, or `derivative` — those are operations, selected with the `operation` parameter.',
144
+ recovery: 'Send the inner expression as `expression` with `operation` set to that function name; for `derivative`, also pass `variable`.',
145
+ },
146
+ {
147
+ reason: 'type_mismatch',
148
+ code: JsonRpcErrorCode.ValidationError,
149
+ thrownBy: 'service',
150
+ when: 'An operand has the wrong type or unit for the operation — a bare number added to a unit, mismatched units, a unit in an exponent, a non-numeric string in arithmetic, or a function used as a value (`5 min`, where `min` is the minimum function; that case carries its own recovery hint).',
151
+ recovery: 'Attach the same unit to the bare operand (`5 kg + 3 kg`) or strip it (`number(5 kg, "kg") + 3`), keep exponents unitless, and use numbers instead of strings.',
152
+ },
153
+ {
154
+ reason: 'evaluation_failed',
155
+ code: JsonRpcErrorCode.ValidationError,
156
+ thrownBy: 'service',
157
+ when: 'The expression parsed but could not be computed — wrong argument count, a value outside the function domain, a singular matrix, mismatched matrix dimensions, or an index out of range — or simplify/derivative cannot process part of it (e.g. a function with no derivative rule).',
158
+ recovery: 'The syntax is valid — fix the argument the error message names (its count, value range, or matrix dimensions) and retry.',
128
159
  },
129
160
  {
130
161
  reason: 'derivative_missing_variable',
@@ -135,6 +166,7 @@ export const calculateTool = tool('calculate', {
135
166
  {
136
167
  reason: 'evaluation_timeout',
137
168
  code: JsonRpcErrorCode.Timeout,
169
+ thrownBy: 'service',
138
170
  when: 'Expression evaluation exceeded the configured timeout (CALC_EVALUATION_TIMEOUT_MS).',
139
171
  retryable: false,
140
172
  recovery: 'Simplify the expression or reduce computational complexity to fit within the timeout.',
@@ -187,12 +219,10 @@ export const calculateTool = tool('calculate', {
187
219
  }
188
220
  },
189
221
  format: (output) => {
190
- const scopeVars = output.scopeVars && output.scopeVars.length > 0 ? output.scopeVars.join(', ') : 'none';
191
- const precision = output.precisionUsed ?? 'full';
192
222
  const lines = [
193
- `**Expression:** \`${output.expression}\``,
223
+ `**Expression:**${labeled(output.expression)}`,
194
224
  `**Operation:** ${output.operation}`,
195
- `**Result:** ${output.result}`,
225
+ `**Result:**${labeled(output.result)}`,
196
226
  `**Type:** ${output.resultType}`,
197
227
  ];
198
228
  if (output.unchanged !== undefined) {
@@ -201,11 +231,49 @@ export const calculateTool = tool('calculate', {
201
231
  ? '**Simplified:** unchanged — expression could not be reduced further'
202
232
  : '**Simplified:** reduced (unchanged: false)');
203
233
  }
204
- if (output.operation !== 'simplify') {
234
+ // Symbolic operations ignore scope and precision, so only evaluate reports them.
235
+ if (output.operation === 'evaluate') {
236
+ const scopeVars = output.scopeVars?.length
237
+ ? output.scopeVars.map(literal).join(', ')
238
+ : 'none';
205
239
  lines.push(`**Scope variables:** ${scopeVars}`);
206
- lines.push(`**Precision:** ${precision}`);
240
+ lines.push(`**Precision:** ${output.precisionUsed ?? 'full'}`);
207
241
  }
208
242
  return [{ type: 'text', text: lines.join('\n') }];
209
243
  },
210
244
  });
245
+ /** Length of the longest run of consecutive backticks in `value` (0 when it has none). */
246
+ function longestBacktickRun(value) {
247
+ return Math.max(0, ...(value.match(/`+/g) ?? []).map((run) => run.length));
248
+ }
249
+ /**
250
+ * Render caller-influenced text so a CommonMark reader sees it byte-for-byte:
251
+ * a code span whose fence is one backtick longer than the value's longest
252
+ * backtick run, space-padded when the value starts or ends with a backtick or
253
+ * space (CommonMark strips one padding space from each side). A value made only
254
+ * of spaces is never stripped, so it goes unpadded; an empty value cannot be a
255
+ * code span and renders as a plain marker. A value with a line break goes in a
256
+ * fenced block on its own lines, sized the same way. No backslash escaping:
257
+ * `*`, `_`, `^`, and `[` are math syntax and must survive a copy. CommonMark
258
+ * normalizes a carriage return to a line feed, so a value holding one (only an
259
+ * expression or scope key can — math.js escapes it in results) reads back with
260
+ * `\n` in its place; `structuredContent` keeps the exact bytes.
261
+ */
262
+ function literal(value) {
263
+ if (value === '')
264
+ return '(empty)';
265
+ const run = longestBacktickRun(value);
266
+ if (/[\r\n]/.test(value)) {
267
+ const fence = '`'.repeat(Math.max(3, run + 1));
268
+ return `\n${fence}\n${value}\n${fence}\n`;
269
+ }
270
+ const fence = '`'.repeat(run + 1);
271
+ const pad = /^[` ]|[` ]$/.test(value) && !/^ +$/.test(value) ? ' ' : '';
272
+ return `${fence}${pad}${value}${pad}${fence}`;
273
+ }
274
+ /** A labeled value: a code span after the label, or a fenced block below it. */
275
+ function labeled(value) {
276
+ const rendered = literal(value);
277
+ return rendered.startsWith('\n') ? rendered.slice(0, -1) : ` ${rendered}`;
278
+ }
211
279
  //# sourceMappingURL=calculate.tool.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"calculate.tool.js","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/calculate.tool.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEjE,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,CAAC,WAAW,EAAE;IAC7C,WAAW,EACT,0NAA0N;IAC5N,WAAW,EAAE;QACX,YAAY,EAAE,IAAI;QAClB,cAAc,EAAE,IAAI;QACpB,aAAa,EAAE,KAAK;KACrB;IACD,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC;QACd,UA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,EAAE,CAAC,CAAC;QAC5C,CAAC;QACD,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpD,CAAC;CACF,CAAC,CAAC"}
1
+ {"version":3,"file":"calculate.tool.js","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/calculate.tool.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAE7F,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,CAAC,WAAW,EAAE;IAC7C,WAAW,EACT,0NAA0N;IAC5N,WAAW,EAAE;QACX,YAAY,EAAE,IAAI;QAClB,cAAc,EAAE,IAAI;QACpB,aAAa,EAAE,KAAK;KACrB;IACD,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC;QACd,UAAU,EAAE,CAAC;aACV,MAAM,EAAE;aACR,GAAG,CAAC,CAAC,CAAC;aACN,QAAQ,CACP,w6BAAw6B,CACz6B;QACH,SAAS,EAAE,CAAC;aACT,IAAI,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,YAAY,CAAC,CAAC;aAC5C,OAAO,CAAC,UAAU,CAAC;aACnB,QAAQ,CACP,+dAA+d,CAChe;QACH,QAAQ,EAAE,CAAC;aACR,KAAK,CAAC;YACL,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,oCAAoC,CAAC;YAC5D,CAAC;iBACE,MAAM,EAAE;iBACR,GAAG,CAAC,EAAE,CAAC;iBACP,KAAK,CACJ,0BAA0B,EAC1B,wDAAwD,CACzD;iBACA,QA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,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;IAClC,MAAM,GAAG,GAAG,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IACxE,OAAO,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,EAAE,CAAC;AAChD,CAAC;AAED,gFAAgF;AAChF,SAAS,OAAO,CAAC,KAAa;IAC5B,MAAM,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IAChC,OAAO,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE,CAAC;AAC5E,CAAC"}
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * @fileoverview Hardened math.js wrapper for secure expression evaluation.
3
3
  * Creates a restricted math.js instance with dangerous functions disabled in
4
- * the expression scope, and wraps evaluation in a vm sandbox with timeout.
4
+ * the expression scope, parses each expression once and checks the tree before
5
+ * anything runs, and evaluates, inspects, and formats the result inside a vm
6
+ * sandbox with a timeout.
5
7
  * @module services/math/math-service
6
8
  */
7
9
  import type { Context } from '@cyanheads/mcp-ts-core';
@@ -10,15 +12,16 @@ import type { MathResult, NumericType } from './types.js';
10
12
  export declare class MathService {
11
13
  /** Default IEEE 754 instance — used for the vast majority of evaluations. */
12
14
  private readonly defaultInstance;
13
- /** BigNumber instance — arbitrary precision; selected via numericType: "BigNumber". */
15
+ /** BigNumber instance — 64 significant digits; selected via numericType: "BigNumber". */
14
16
  private readonly bigNumberInstance;
15
17
  /** Fraction instance — exact rational arithmetic; selected via numericType: "Fraction". */
16
18
  private readonly fractionInstance;
17
- private readonly parse;
18
19
  private readonly simplify;
19
20
  private readonly derivative;
20
21
  private readonly simplifyRules;
21
22
  private readonly config;
23
+ /** vm context reused by every timed call; see {@link runWithTimeout}. */
24
+ private readonly sandbox;
22
25
  constructor(config: ServerConfig);
23
26
  /** Select the pre-initialized evaluate/format/typeOf bundle for a given numeric type. */
24
27
  private instanceFor;
@@ -31,36 +34,72 @@ export declare class MathService {
31
34
  /** Get formatted help content listing available functions, operators, and syntax. */
32
35
  getHelpContent(): string;
33
36
  private validateInput;
37
+ /**
38
+ * Parse once and check the tree before anything evaluates. A parse failure is
39
+ * `parse_failed`. Multiple statements are detected structurally — math.js parses
40
+ * `a; b` and a top-level newline into a `BlockNode` — so `;` inside a matrix or
41
+ * inside either quote style (`"a;b"`, `'a;b'`) is data, transpose `A'` stays an
42
+ * operator, and a real separator is rejected before either statement runs (#32).
43
+ * math.js treats a bare carriage return as a syntax error rather than a
44
+ * separator; when it is what broke the parse, the input is re-parsed with line
45
+ * feeds purely to report `multiple_expressions` — the rewritten text is never
46
+ * evaluated. The same tree then gets the stringifier check, the
47
+ * operation-as-function check (#27), and the notation rename (#24), and yields
48
+ * the names it uses as values that resolve to functions (#38). Every operation
49
+ * starts here, so it also resets the instance's auto unit system (#37).
50
+ */
51
+ private parseExpression;
52
+ /** Whether `expression` parses to multiple statements. */
53
+ private parsesAsBlock;
54
+ private multipleExpressions;
34
55
  /** Reject scope keys that could pollute the object prototype chain. */
35
56
  private validateScope;
36
57
  /** Reject result types that leak internals (functions, parsers, multi-expression ResultSets). */
37
58
  private validateResultType;
38
- /** Reject results holding a non-finite value (Infinity, -Infinity, NaN), including inside matrices and complex numbers. */
39
- private validateFinite;
59
+ /**
60
+ * Inspect a result before it is formatted: reject a `help()` object (its
61
+ * rendering evaluates the documentation examples, #31), a collection too large
62
+ * to ever fit `maxResultLength` (checked before formatting, so it is never
63
+ * stringified), any non-finite number, scalar or nested (#21), and under
64
+ * numericType "Fraction", any float approximation, scalar or nested (#35).
65
+ */
66
+ private validateResultValue;
40
67
  /** Reject results that exceed the configured maximum size. */
41
68
  private validateResultSize;
69
+ private resultTooLarge;
42
70
  /**
43
- * Reject expressions that access `.toString` / `.toLocaleString` on any value.
44
- * math.js permits these methods on function-valued identifiers (`cos.toString()`,
45
- * `import.toString()`), returning the function's source as a plain string — which
46
- * slips past {@link validateResultType}, whose function defense only inspects the
47
- * value AFTER stringification. The check is parse-time and AST-based rather than a
48
- * runtime `Function.prototype` patch: math.js itself calls `toString` on functions
49
- * internally while evaluating units, statistics, and complex results, so patching
50
- * the prototype would reject legitimate expressions. No real calculator expression
51
- * needs `.toString()`/`.toLocaleString()`, so blocking the accessor outright (dot
52
- * or bracket form, on any operand) is both sufficient and side-effect-free. String
53
- * literals that merely contain the text "toString" parse as ConstantNodes, not
54
- * accessors, so they are unaffected.
71
+ * Runs a synchronous function inside a vm sandbox with timeout protection and
72
+ * maps anything it throws to a declared reason via {@link classifyFailure}.
73
+ *
74
+ * The context exists only to carry the timeout — `fn` and everything it calls
75
+ * run in this realm — so one context is reused for every call and cleared
76
+ * afterwards. A fresh context per call costs ~100 µs and, under Bun, retains
77
+ * ~100 KB of memory per call.
55
78
  */
56
- private validateNoFunctionStringification;
79
+ private runWithTimeout;
57
80
  /**
58
- * Runs a synchronous function inside a vm sandbox with timeout protection.
59
- * `numericType` is supplied only by the evaluate path so a Fraction-mode
60
- * conversion failure can be remapped to the actionable `fraction_unsupported`
61
- * error instead of the misleading `parse_failed` (#19).
81
+ * Classify a failure raised after the expression parsed (evaluation, result
82
+ * inspection, formatting, or a symbolic operation). First match wins:
83
+ *
84
+ * 1. Already-classified `McpError`s (result checks) pass through.
85
+ * 2. Timeout → `evaluation_timeout`.
86
+ * 3. A size guard (see size-guard.ts) → `result_too_large`.
87
+ * 4. Fraction mode calling a function with no Fraction implementation (sqrt,
88
+ * sin, log, factorial, …) → `fraction_unsupported` (#19); so does Fraction
89
+ * mode meeting a float with no equal Fraction (`pi * 2/3`, #35).
90
+ * 5. fraction.js `Division by Zero`, in any numericType → `undefined_result` (#21).
91
+ * 6. Name errors (undefined symbol/function/unit, disabled function, blocked
92
+ * property) → `parse_failed`.
93
+ * 7. A symbolic operation (simplify, derivative) that cannot process the parsed
94
+ * tree → `evaluation_failed`, with a hint about the symbolic engine rather
95
+ * than about argument values (see {@link symbolicFailure}).
96
+ * 8. Operand type/unit errors (typed-function `wrongType`, unit mismatch,
97
+ * string-to-number) → `type_mismatch`.
98
+ * 9. Anything else — arity, domain, singular matrix, dimensions, index →
99
+ * `evaluation_failed` (#29). Stage decides, not error class: a runtime
100
+ * `SyntaxError` such as `number("abc")` lands here, never in `parse_failed`.
62
101
  */
63
- private runWithTimeout;
102
+ private classifyFailure;
64
103
  }
65
104
  /** Initialize the math service. Call once from createApp setup(). */
66
105
  export declare function initMathService(config: ServerConfig): void;
@@ -1 +1 @@
1
- {"version":3,"file":"math-service.d.ts","sourceRoot":"","sources":["../../../src/services/math/math-service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAGtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAgT1D,qBAAa,WAAW;IACtB,6EAA6E;IAC7E,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAe;IAC/C,uFAAuF;IACvF,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAe;IACjD,2FAA2F;IAC3F,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAe;IAEhD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA6B;IACnD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAmE;IAC5F,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA6D;IACxF,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAiB;IAC/C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAe;IAEtC,YAAY,MAAM,EAAE,YAAY,EAmB/B;IA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