-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·604 lines (545 loc) · 17.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
#!/usr/bin/env node
import { genkit, z } from 'genkit';
import { mcpServer } from 'genkitx-mcp';
import * as math from 'mathjs';
const ai = genkit({});
// Helper functions for mathematical operations
const derivative = (expr, variable = 'x') => {
try {
const node = math.parse(expr);
const derivativeExpr = math.derivative(node, variable);
return derivativeExpr.toString();
} catch (e) {
return `Error: ${e.message}`;
}
};
const integral = (expr, variable = 'x') => {
try {
// For basic polynomials
const powerMatch = expr.match(new RegExp(`${variable}\\^(\\d+)`));
if (powerMatch) {
const n = parseInt(powerMatch[1]);
return `${variable}^${n + 1}/${n + 1}`;
}
// For basic functions
const rules = {
'e^x': 'e^x',
'1/x': `ln|${variable}|`,
[`sin(${variable})`]: `-cos(${variable})`,
[`cos(${variable})`]: `sin(${variable})`,
'x': 'x^2/2'
};
return rules[expr] || 'Cannot compute integral';
} catch (e) {
return `Error: ${e.message}`;
}
};
const riemannSum = (expr, variable, a, b, n, method = 'midpoint') => {
try {
const deltaX = (b - a) / n;
let sum = 0;
const node = math.parse(expr);
const scope = {};
if (method === 'left' || method === 'right') {
const offset = method === 'right' ? 1 : 0;
for (let i = 0; i < n; i++) {
const x = a + (i + offset) * deltaX;
scope[variable] = x;
sum += math.evaluate(node, scope) * deltaX;
}
} else if (method === 'midpoint') {
for (let i = 0; i < n; i++) {
const x = a + (i + 0.5) * deltaX;
scope[variable] = x;
sum += math.evaluate(node, scope) * deltaX;
}
} else if (method === 'trapezoid') {
for (let i = 0; i <= n; i++) {
const x = a + i * deltaX;
scope[variable] = x;
const coef = (i === 0 || i === n) ? 0.5 : 1;
sum += coef * math.evaluate(node, scope) * deltaX;
}
}
return sum;
} catch (e) {
return `Error: ${e.message}`;
}
};
// Define mathematical tools
ai.defineTool(
{
name: 'derivative',
description: 'Calculate the derivative of a mathematical expression',
inputSchema: z.object({
expression: z.string().describe('Mathematical expression (e.g., "x^2", "e^x", "sin(x)")'),
variable: z.string().optional().describe('Variable to differentiate with respect to (default: x)')
}),
outputSchema: z.string(),
},
async ({ expression, variable = 'x' }) => {
return derivative(expression, variable);
}
);
ai.defineTool(
{
name: 'integral',
description: 'Calculate the indefinite integral of a mathematical expression',
inputSchema: z.object({
expression: z.string().describe('Mathematical expression (e.g., "x^2", "e^x", "sin(x)")'),
variable: z.string().optional().describe('Variable to integrate with respect to (default: x)')
}),
outputSchema: z.string(),
},
async ({ expression, variable = 'x' }) => {
return integral(expression, variable);
}
);
ai.defineTool(
{
name: 'riemann_sum',
description: 'Calculate the Riemann sum of a function using different methods',
inputSchema: z.object({
expression: z.string().describe('Function to integrate'),
variable: z.string().describe('Variable of integration'),
a: z.number().describe('Lower limit of integration'),
b: z.number().describe('Upper limit of integration'),
n: z.number().describe('Number of subintervals'),
method: z.enum(['left', 'right', 'midpoint', 'trapezoid']).default('midpoint')
.describe('Method: left, right, midpoint, or trapezoid')
}),
outputSchema: z.number(),
},
async ({ expression, variable, a, b, n, method }) => {
return riemannSum(expression, variable, a, b, n, method);
}
);
ai.defineTool(
{
name: 'area',
description: 'Calculate the area under a curve between two points',
inputSchema: z.object({
expression: z.string(),
start: z.number(),
end: z.number(),
n: z.number().optional().describe('Number of subintervals (default: 1000)')
}),
outputSchema: z.number(),
},
async ({ expression, start, end, n = 1000 }) => {
return riemannSum(expression, 'x', start, end, n, 'trapezoid');
}
);
ai.defineTool(
{
name: 'volume',
description: 'Calculate the volume of revolution around x-axis',
inputSchema: z.object({
expression: z.string(),
start: z.number(),
end: z.number()
}),
outputSchema: z.number(),
},
async ({ expression, start, end }) => {
// Volume of revolution using disk method
const steps = 1000;
const dx = (end - start) / steps;
let volume = 0;
for (let i = 0; i < steps; i++) {
const x = start + i * dx;
const y = eval(expression.replace(/x/g, `(${x})`));
volume += Math.PI * y * y * dx;
}
return volume;
}
);
ai.defineTool(
{
name: 'logarithm',
description: 'Calculate logarithm with any base',
inputSchema: z.object({
value: z.number(),
base: z.number().optional()
}),
outputSchema: z.number(),
},
async ({ value, base = Math.E }) => {
return Math.log(value) / Math.log(base);
}
);
ai.defineTool(
{
name: 'exponential',
description: 'Calculate exponential function (e^x)',
inputSchema: z.object({
power: z.number()
}),
outputSchema: z.number(),
},
async ({ power }) => {
return Math.exp(power);
}
);
// Financial analysis tools
ai.defineTool(
{
name: 'compound_interest',
description: 'Calculate compound interest',
inputSchema: z.object({
principal: z.number(),
rate: z.number(), // annual interest rate as decimal
time: z.number(), // years
compounds: z.number().optional() // times per year
}),
outputSchema: z.number(),
},
async ({ principal, rate, time, compounds = 12 }) => {
return principal * Math.pow(1 + rate/compounds, compounds * time);
}
);
ai.defineTool(
{
name: 'present_value',
description: 'Calculate present value of future cash flows',
inputSchema: z.object({
futureValue: z.number(),
rate: z.number(), // discount rate as decimal
time: z.number() // years
}),
outputSchema: z.number(),
},
async ({ futureValue, rate, time }) => {
return futureValue / Math.pow(1 + rate, time);
}
);
ai.defineTool(
{
name: 'npv',
description: 'Calculate Net Present Value of cash flows',
inputSchema: z.object({
cashFlows: z.array(z.number()),
rate: z.number() // discount rate as decimal
}),
outputSchema: z.number(),
},
async ({ cashFlows, rate }) => {
return cashFlows.reduce((npv, cf, t) =>
npv + cf / Math.pow(1 + rate, t), 0);
}
);
const darbouxSum = (expr, variable, a, b, n, type = 'upper') => {
try {
const deltaX = (b - a) / n;
let sum = 0;
const node = math.parse(expr);
const scope = {};
for (let i = 0; i < n; i++) {
const x1 = a + i * deltaX;
const x2 = x1 + deltaX;
scope[variable] = x1;
const y1 = math.evaluate(node, scope);
scope[variable] = x2;
const y2 = math.evaluate(node, scope);
const value = type === 'upper' ? Math.max(y1, y2) : Math.min(y1, y2);
sum += value * deltaX;
}
return sum;
} catch (e) {
return `Error: ${e.message}`;
}
};
const findLimit = (expr, variable, approach) => {
try {
const node = math.parse(expr);
const scope = {};
const epsilon = 1e-10;
// Evaluate near the approach point
scope[variable] = approach + epsilon;
const rightLimit = math.evaluate(node, scope);
scope[variable] = approach - epsilon;
const leftLimit = math.evaluate(node, scope);
// Check if limits from both sides are approximately equal
if (Math.abs(rightLimit - leftLimit) < epsilon) {
return (rightLimit + leftLimit) / 2;
}
return 'Limit does not exist';
} catch (e) {
return `Error: ${e.message}`;
}
};
// Define additional calculus tools
ai.defineTool(
{
name: 'darboux_sum',
description: 'Calculate the Darboux sum of a function',
inputSchema: z.object({
expression: z.string().describe('Function to integrate'),
variable: z.string().describe('Variable of integration'),
a: z.number().describe('Lower limit of integration'),
b: z.number().describe('Upper limit of integration'),
n: z.number().describe('Number of subintervals'),
type: z.enum(['upper', 'lower']).default('upper')
.describe('Type: upper or lower Darboux sum')
}),
outputSchema: z.union([z.number(), z.string()]),
},
async ({ expression, variable, a, b, n, type }) => {
return darbouxSum(expression, variable, a, b, n, type);
}
);
ai.defineTool(
{
name: 'limit',
description: 'Calculate the limit of a function as it approaches a value',
inputSchema: z.object({
expression: z.string().describe('Function to evaluate limit'),
variable: z.string().describe('Variable approaching the limit'),
approach: z.number().describe('Value the variable approaches')
}),
outputSchema: z.union([z.number(), z.string()]),
},
async ({ expression, variable, approach }) => {
return findLimit(expression, variable, approach);
}
);
ai.defineTool(
{
name: 'solve',
description: 'Solve an equation for a variable',
inputSchema: z.object({
expression: z.string().describe('Equation to solve (e.g., "x^2 = 4")'),
variable: z.string().describe('Variable to solve for')
}),
outputSchema: z.array(z.string()),
},
async ({ expression, variable }) => {
try {
// Convert equation to standard form (expression = 0)
const sides = expression.split('=').map(s => s.trim());
if (sides.length !== 2) {
throw new Error('Invalid equation format. Use "expression = value"');
}
const equationNode = math.parse(`${sides[0]}-(${sides[1]})`);
const solutions = math.solve(equationNode, variable);
return solutions.map(sol => sol.toString());
} catch (e) {
return [`Error: ${e.message}`];
}
}
);
// Engineering functions
const laplaceTransform = (expr, t, s) => {
try {
const node = math.parse(expr);
// Using numerical integration for a basic approximation
const upperLimit = 100; // Approximation of infinity
const steps = 1000;
const dt = upperLimit / steps;
let result = math.complex(0, 0);
for (let i = 0; i < steps; i++) {
const time = i * dt;
const scope = { [t]: time };
const ft = math.evaluate(node, scope);
const expTerm = math.exp(math.multiply(math.complex(-s, 0), time));
result = math.add(result,
math.multiply(ft, expTerm, dt));
}
return result.toString();
} catch (e) {
return `Error: ${e.message}`;
}
};
const fourierTransform = (expr, t, omega) => {
try {
const node = math.parse(expr);
// Using numerical integration for a basic approximation
const limit = 50; // Approximation of infinity
const steps = 1000;
const dt = (2 * limit) / steps;
let result = math.complex(0, 0);
for (let i = 0; i < steps; i++) {
const time = -limit + i * dt;
const scope = { [t]: time };
const ft = math.evaluate(node, scope);
const expTerm = math.exp(
math.multiply(
math.complex(0, -1),
omega,
time
)
);
result = math.add(result,
math.multiply(ft, expTerm, dt));
}
return result.toString();
} catch (e) {
return `Error: ${e.message}`;
}
};
const zTransform = (expr, n, z, limit = 100) => {
try {
const node = math.parse(expr);
let result = math.complex(0, 0);
for (let k = 0; k <= limit; k++) {
const scope = { [n]: k };
const fn = math.evaluate(node, scope);
const zTerm = math.pow(z, -k);
result = math.add(result, math.multiply(fn, zTerm));
}
return result.toString();
} catch (e) {
return `Error: ${e.message}`;
}
};
// Engineering transform tools
ai.defineTool(
{
name: 'laplace_transform',
description: 'Calculate the Laplace transform of a function',
inputSchema: z.object({
expression: z.string().describe('Function of time'),
timeVar: z.string().describe('Time variable'),
laplaceVar: z.string().describe('Laplace variable')
}),
outputSchema: z.string(),
},
async ({ expression, timeVar, laplaceVar }) => {
return laplaceTransform(expression, timeVar, laplaceVar);
}
);
ai.defineTool(
{
name: 'fourier_transform',
description: 'Calculate the Fourier transform of a function',
inputSchema: z.object({
expression: z.string().describe('Function of time'),
timeVar: z.string().describe('Time variable'),
freqVar: z.string().describe('Frequency variable')
}),
outputSchema: z.string(),
},
async ({ expression, timeVar, freqVar }) => {
return fourierTransform(expression, timeVar, freqVar);
}
);
ai.defineTool(
{
name: 'z_transform',
description: 'Calculate the Z-transform of a function',
inputSchema: z.object({
expression: z.string().describe('Function of discrete time'),
timeVar: z.string().describe('Discrete time variable'),
zVar: z.string().describe('Z-transform variable'),
limit: z.number().optional().describe('Upper limit for summation (default: 100)')
}),
outputSchema: z.string(),
},
async ({ expression, timeVar, zVar, limit = 100 }) => {
return zTransform(expression, timeVar, zVar, limit);
}
);
// Financial helper functions
const normalCDF = (x) => {
const t = 1 / (1 + 0.2316419 * Math.abs(x));
const d = 0.3989423 * Math.exp(-x * x / 2);
const p = d * t * (0.319381530 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))));
return x >= 0 ? 1 - p : p;
};
const normalPDF = (x) => {
return (1 / Math.sqrt(2 * Math.PI)) * Math.exp(-0.5 * x * x);
};
const blackScholes = (S, K, T, r, sigma, optionType = 'call') => {
try {
const d1 = (Math.log(S / K) + (r + 0.5 * sigma * sigma) * T) / (sigma * Math.sqrt(T));
const d2 = d1 - sigma * Math.sqrt(T);
if (optionType === 'call') {
return S * normalCDF(d1) - K * Math.exp(-r * T) * normalCDF(d2);
} else if (optionType === 'put') {
return K * Math.exp(-r * T) * normalCDF(-d2) - S * normalCDF(-d1);
} else {
throw new Error('Invalid option type. Must be "call" or "put".');
}
} catch (e) {
return `Error: ${e.message}`;
}
};
const optionGreeks = (S, K, T, r, sigma, optionType = 'call') => {
try {
const d1 = (Math.log(S / K) + (r + 0.5 * sigma * sigma) * T) / (sigma * Math.sqrt(T));
const d2 = d1 - sigma * Math.sqrt(T);
let delta, gamma, vega, theta, rho;
if (optionType === 'call') {
delta = normalCDF(d1);
gamma = normalPDF(d1) / (S * sigma * Math.sqrt(T));
vega = S * normalPDF(d1) * Math.sqrt(T);
theta = -(S * normalPDF(d1) * sigma) / (2 * Math.sqrt(T)) -
r * K * Math.exp(-r * T) * normalCDF(d2);
rho = K * T * Math.exp(-r * T) * normalCDF(d2);
} else if (optionType === 'put') {
delta = normalCDF(d1) - 1;
gamma = normalPDF(d1) / (S * sigma * Math.sqrt(T));
vega = S * normalPDF(d1) * Math.sqrt(T);
theta = -(S * normalPDF(d1) * sigma) / (2 * Math.sqrt(T)) +
r * K * Math.exp(-r * T) * normalCDF(-d2);
rho = -K * T * Math.exp(-r * T) * normalCDF(-d2);
} else {
throw new Error('Invalid option type. Must be "call" or "put".');
}
return { delta, gamma, vega, theta, rho };
} catch (e) {
return `Error: ${e.message}`;
}
};
// Define additional financial tools
ai.defineTool(
{
name: 'black_scholes',
description: 'Calculate Black-Scholes option price',
inputSchema: z.object({
S: z.number().describe('Current price of the asset'),
K: z.number().describe('Strike price of the option'),
T: z.number().describe('Time to expiration in years'),
r: z.number().describe('Risk-free interest rate'),
sigma: z.number().describe('Volatility of the asset'),
optionType: z.enum(['call', 'put']).default('call')
.describe('Option type: "call" or "put"')
}),
outputSchema: z.union([z.number(), z.string()]),
},
async ({ S, K, T, r, sigma, optionType }) => {
return blackScholes(S, K, T, r, sigma, optionType);
}
);
ai.defineTool(
{
name: 'option_greeks',
description: 'Calculate the Greeks for a Black-Scholes option',
inputSchema: z.object({
S: z.number().describe('Current price of the asset'),
K: z.number().describe('Strike price of the option'),
T: z.number().describe('Time to expiration in years'),
r: z.number().describe('Risk-free interest rate'),
sigma: z.number().describe('Volatility of the asset'),
optionType: z.enum(['call', 'put']).default('call')
.describe('Option type: "call" or "put"')
}),
outputSchema: z.union([
z.object({
delta: z.number(),
gamma: z.number(),
vega: z.number(),
theta: z.number(),
rho: z.number()
}),
z.string()
]),
},
async ({ S, K, T, r, sigma, optionType }) => {
return optionGreeks(S, K, T, r, sigma, optionType);
}
);
const server = mcpServer(ai, { name: 'genkit_mcp', version: '0.1.0' });
server.start();
// Log when server starts
console.log('Genkit MCP server started. Waiting for connections...');