@smnpm1/prism-mcp 0.0.0-stage → 0.7.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.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +103 -2
  3. package/config.example.json +16 -0
  4. package/demo/README.md +5 -0
  5. package/demo/folioprism/analysis-merged.json +2017 -0
  6. package/demo/folioprism/analysis.json +2025 -0
  7. package/demo/folioprism/drift.json +110 -0
  8. package/demo/folioprism/exposure/AAPL.json +31 -0
  9. package/demo/folioprism/exposure/ABBV.json +27 -0
  10. package/demo/folioprism/exposure/ABT.json +31 -0
  11. package/demo/folioprism/exposure/ADI.json +31 -0
  12. package/demo/folioprism/exposure/ADP.json +35 -0
  13. package/demo/folioprism/exposure/AMAT.json +31 -0
  14. package/demo/folioprism/exposure/AMD.json +31 -0
  15. package/demo/folioprism/exposure/AMGN.json +35 -0
  16. package/demo/folioprism/exposure/AMZN.json +31 -0
  17. package/demo/folioprism/exposure/AVGO.json +31 -0
  18. package/demo/folioprism/exposure/BMY.json +31 -0
  19. package/demo/folioprism/exposure/BRK.B.json +27 -0
  20. package/demo/folioprism/exposure/CAT.json +27 -0
  21. package/demo/folioprism/exposure/CMCSA.json +35 -0
  22. package/demo/folioprism/exposure/COP.json +31 -0
  23. package/demo/folioprism/exposure/COST.json +31 -0
  24. package/demo/folioprism/exposure/CRWD.json +31 -0
  25. package/demo/folioprism/exposure/CSCO.json +31 -0
  26. package/demo/folioprism/exposure/CVX.json +31 -0
  27. package/demo/folioprism/exposure/GILD.json +31 -0
  28. package/demo/folioprism/exposure/GOOG.json +31 -0
  29. package/demo/folioprism/exposure/GOOGL.json +31 -0
  30. package/demo/folioprism/exposure/HD.json +31 -0
  31. package/demo/folioprism/exposure/INTC.json +31 -0
  32. package/demo/folioprism/exposure/JNJ.json +27 -0
  33. package/demo/folioprism/exposure/JPM.json +27 -0
  34. package/demo/folioprism/exposure/KLAC.json +31 -0
  35. package/demo/folioprism/exposure/KO.json +31 -0
  36. package/demo/folioprism/exposure/LIN.json +31 -0
  37. package/demo/folioprism/exposure/LLY.json +27 -0
  38. package/demo/folioprism/exposure/LRCX.json +31 -0
  39. package/demo/folioprism/exposure/META.json +31 -0
  40. package/demo/folioprism/exposure/MRK.json +31 -0
  41. package/demo/folioprism/exposure/MSFT.json +31 -0
  42. package/demo/folioprism/exposure/MU.json +31 -0
  43. package/demo/folioprism/exposure/NFLX.json +31 -0
  44. package/demo/folioprism/exposure/NVDA.json +31 -0
  45. package/demo/folioprism/exposure/PANW.json +31 -0
  46. package/demo/folioprism/exposure/PEP.json +35 -0
  47. package/demo/folioprism/exposure/PG.json +31 -0
  48. package/demo/folioprism/exposure/PLTR.json +31 -0
  49. package/demo/folioprism/exposure/QCOM.json +35 -0
  50. package/demo/folioprism/exposure/SNDK.json +31 -0
  51. package/demo/folioprism/exposure/SPCX.json +27 -0
  52. package/demo/folioprism/exposure/TSLA.json +31 -0
  53. package/demo/folioprism/exposure/TXN.json +35 -0
  54. package/demo/folioprism/exposure/UNH.json +31 -0
  55. package/demo/folioprism/exposure/V.json +27 -0
  56. package/demo/folioprism/exposure/VZ.json +31 -0
  57. package/demo/folioprism/exposure/WMT.json +31 -0
  58. package/demo/folioprism/exposure/XOM.json +27 -0
  59. package/demo/folioprism/exposure-not-held.json +18 -0
  60. package/demo/signalprism/clusters.json +40 -0
  61. package/demo/signalprism/not-tracked.json +6 -0
  62. package/demo/signalprism/signals.json +1070 -0
  63. package/demo/signalprism/status.json +16 -0
  64. package/demo/signalprism/ticker/ACMR.json +248 -0
  65. package/demo/signalprism/ticker/BFLD.json +72 -0
  66. package/demo/signalprism/ticker/CAT.json +81 -0
  67. package/demo/signalprism/ticker/CDWD.json +67 -0
  68. package/demo/signalprism/ticker/DNMF.json +70 -0
  69. package/demo/signalprism/ticker/EVMD.json +111 -0
  70. package/demo/signalprism/ticker/FLCN.json +78 -0
  71. package/demo/signalprism/ticker/GSBD.json +81 -0
  72. package/demo/signalprism/ticker/HLCM.json +86 -0
  73. package/demo/signalprism/ticker/HLFD.json +82 -0
  74. package/demo/signalprism/ticker/HLFN.json +78 -0
  75. package/demo/signalprism/ticker/IRBK.json +84 -0
  76. package/demo/signalprism/ticker/IRBR.json +72 -0
  77. package/demo/signalprism/ticker/SPG.json +45 -0
  78. package/dist/apps.js +13 -0
  79. package/dist/config.js +99 -0
  80. package/dist/demo.js +92 -0
  81. package/dist/folioprism/client.js +42 -0
  82. package/dist/folioprism/drift-schema.js +35 -0
  83. package/dist/folioprism/exposure-schema.js +28 -0
  84. package/dist/folioprism/schema.js +85 -0
  85. package/dist/http.js +54 -0
  86. package/dist/index.js +14 -0
  87. package/dist/log.js +22 -0
  88. package/dist/privacy.js +11 -0
  89. package/dist/server.js +31 -0
  90. package/dist/signalprism/client.js +34 -0
  91. package/dist/signalprism/schema.js +221 -0
  92. package/dist/signalprism/time.js +31 -0
  93. package/dist/tools/folioprism/data-quality.js +76 -0
  94. package/dist/tools/folioprism/drift.js +96 -0
  95. package/dist/tools/folioprism/exposure-lookup.js +27 -0
  96. package/dist/tools/folioprism/fund-overlap.js +55 -0
  97. package/dist/tools/folioprism/index.js +17 -0
  98. package/dist/tools/folioprism/prism-view.js +74 -0
  99. package/dist/tools/folioprism/shared.js +66 -0
  100. package/dist/tools/folioprism/stock-exposure.js +51 -0
  101. package/dist/tools/folioprism/summary.js +75 -0
  102. package/dist/tools/folioprism/top-stocks.js +48 -0
  103. package/dist/tools/overview/insider.js +60 -0
  104. package/dist/tools/overview/portfolio.js +57 -0
  105. package/dist/tools/overview/ticker-overview.js +84 -0
  106. package/dist/tools/register.js +59 -0
  107. package/dist/tools/result.js +4 -0
  108. package/dist/tools/signalprism/clusters.js +24 -0
  109. package/dist/tools/signalprism/index.js +11 -0
  110. package/dist/tools/signalprism/recent.js +38 -0
  111. package/dist/tools/signalprism/shared.js +167 -0
  112. package/dist/tools/signalprism/status.js +90 -0
  113. package/dist/tools/signalprism/ticker.js +30 -0
  114. package/dist/tools/status.js +100 -0
  115. package/dist/tools/ticker-input.js +3 -0
  116. package/package.json +57 -4
package/dist/config.js ADDED
@@ -0,0 +1,99 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, relative } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import * as z from "zod";
7
+ import { APP_TOOLS } from "./apps.js";
8
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
9
+ /** The prism-mcp folder: the parent of `src/` or `dist/`. */
10
+ export const PACKAGE_ROOT = fileURLToPath(new URL("..", import.meta.url));
11
+ const AppSchema = z.object({
12
+ enabled: z.boolean().default(true),
13
+ baseUrl: z.url(),
14
+ tools: z.record(z.string(), z.boolean()).default({}),
15
+ });
16
+ const SAMPLE_FOLIOPRISM = { enabled: true, baseUrl: "http://127.0.0.1:8420", tools: {} };
17
+ const SAMPLE_SIGNALPRISM_URL = "http://127.0.0.1:8500";
18
+ const SAMPLE_SIGNALPRISM = { enabled: false, baseUrl: SAMPLE_SIGNALPRISM_URL, tools: {} };
19
+ const SignalPrismSchema = AppSchema.extend({ baseUrl: z.url().default(SAMPLE_SIGNALPRISM_URL) });
20
+ const ConfigSchema = z.object({
21
+ detail: z.enum(["percent", "full"]).default("percent"),
22
+ apps: z
23
+ .object({
24
+ folioprism: AppSchema.default(SAMPLE_FOLIOPRISM),
25
+ signalprism: SignalPrismSchema.default(SAMPLE_SIGNALPRISM),
26
+ })
27
+ .default({ folioprism: SAMPLE_FOLIOPRISM, signalprism: SAMPLE_SIGNALPRISM }),
28
+ logDir: z.string().default("~/.prism-mcp/logs"),
29
+ });
30
+ function refuse(reason) {
31
+ throw new Error(`Refusing to start: ${reason}`);
32
+ }
33
+ /** Throw unless the URL's host is loopback. */
34
+ export function assertLoopback(url) {
35
+ const host = new URL(url).hostname;
36
+ if (!LOOPBACK_HOSTS.has(host))
37
+ refuse(`${url} is not a loopback address (127.0.0.1, localhost or [::1]).`);
38
+ }
39
+ function assertKnownTools(app, tools) {
40
+ for (const name of Object.keys(tools)) {
41
+ if (!APP_TOOLS[app].includes(name))
42
+ refuse(`unknown tool in config: apps.${app}.tools.${name}`);
43
+ }
44
+ }
45
+ function assertOutsidePackage(logDir) {
46
+ if (!isAbsolute(logDir))
47
+ refuse(`logDir must be an absolute path or start with ~, got ${logDir}`);
48
+ const rel = relative(PACKAGE_ROOT, logDir);
49
+ if (rel === "" || (!rel.startsWith("..") && !isAbsolute(rel))) {
50
+ refuse(`logDir must be outside the prism-mcp folder, got ${logDir}`);
51
+ }
52
+ }
53
+ /** Validate raw config, expand `~` in logDir and enforce the loopback, tool-name and logDir guards. */
54
+ export function parseConfig(raw) {
55
+ const result = ConfigSchema.safeParse(raw);
56
+ if (!result.success) {
57
+ const issue = result.error.issues[0];
58
+ refuse(`invalid config at ${issue.path.join(".") || "(root)"}: ${issue.message}`);
59
+ }
60
+ const config = result.data;
61
+ for (const [name, app] of Object.entries(config.apps)) {
62
+ assertLoopback(app.baseUrl);
63
+ assertKnownTools(name, app.tools);
64
+ }
65
+ const logDir = config.logDir.replace(/^~(?=$|[/\\])/, homedir());
66
+ assertOutsidePackage(logDir);
67
+ return { ...config, logDir };
68
+ }
69
+ function readConfigFile(path) {
70
+ let text;
71
+ try {
72
+ text = readFileSync(path, "utf8");
73
+ }
74
+ catch {
75
+ refuse(`config file not found or unreadable: ${path}`);
76
+ }
77
+ try {
78
+ return JSON.parse(text);
79
+ }
80
+ catch {
81
+ refuse(`config file is not valid JSON: ${path}`);
82
+ }
83
+ }
84
+ /** Demo mode: both apps on, detail percent, answered from the bundled captures. */
85
+ function demoConfig() {
86
+ const apps = { folioprism: SAMPLE_FOLIOPRISM, signalprism: { ...SAMPLE_SIGNALPRISM, enabled: true } };
87
+ return { ...parseConfig({ apps }), demo: true };
88
+ }
89
+ /**
90
+ * Load config from the file named by `--config <path>`, else PRISM_MCP_CONFIG,
91
+ * or use the sample-stack defaults when neither is set. `--demo` ignores both and refuses if either is given.
92
+ */
93
+ export function loadConfig(env = process.env, argv = process.argv.slice(2)) {
94
+ const { values } = parseArgs({ args: argv, options: { config: { type: "string" }, demo: { type: "boolean" } } });
95
+ const path = values.config ?? env.PRISM_MCP_CONFIG;
96
+ if (values.demo)
97
+ return path === undefined ? demoConfig() : refuse("--demo can't be combined with --config or PRISM_MCP_CONFIG.");
98
+ return parseConfig(path === undefined ? {} : readConfigFile(path));
99
+ }
package/dist/demo.js ADDED
@@ -0,0 +1,92 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { PACKAGE_ROOT } from "./config.js";
4
+ import { etToIso } from "./signalprism/time.js";
5
+ import { NotFoundError, PrismAppError } from "./http.js";
6
+ export const DEMO_LABEL = "DEMO DATA: sample portfolio and made-up insider filings.";
7
+ const DEMO_DIR = join(PACKAGE_ROOT, "demo");
8
+ const DEFAULT_DAYS = 30;
9
+ const DAY_MS = 86_400_000;
10
+ function read(file) {
11
+ return JSON.parse(readFileSync(join(DEMO_DIR, file), "utf8"));
12
+ }
13
+ /** The first day to include: `days` before the capture's own date, so the demo never ages out. */
14
+ function cutoff(asOf, days) {
15
+ return new Date(Date.parse(asOf.slice(0, 10)) - days * DAY_MS).toISOString().slice(0, 10);
16
+ }
17
+ /** The demo's clock: the moment of the capture, so ages and freshness never change as the demo gets older. */
18
+ export function demoNow() {
19
+ return Date.parse(etToIso(read("signalprism/status.json").as_of));
20
+ }
21
+ const num = (value) => (value === null ? undefined : Number(value));
22
+ function exposure(params) {
23
+ const ticker = (params.get("ticker") ?? "").toUpperCase();
24
+ const file = `folioprism/exposure/${ticker}.json`;
25
+ if (/^[A-Z0-9.-]+$/.test(ticker) && existsSync(join(DEMO_DIR, file)))
26
+ return read(file);
27
+ const notHeld = read("folioprism/exposure-not-held.json");
28
+ notHeld.results[0].ticker = ticker;
29
+ return notHeld;
30
+ }
31
+ function signals(params) {
32
+ const doc = read("signalprism/signals.json");
33
+ const days = num(params.get("days")) ?? DEFAULT_DAYS;
34
+ const minScore = num(params.get("minScore")) ?? 0;
35
+ const role = params.get("role");
36
+ const heldOnly = params.get("heldOnly") === "true";
37
+ const includePlan = params.get("includePlan") === "true";
38
+ const includeRoundTrips = params.get("includeRoundTrips") === "true";
39
+ const first = cutoff(doc.as_of, days);
40
+ const rows = doc.signals.filter((s) => s.filed_at >= first &&
41
+ s.score >= minScore &&
42
+ (role === null || s.role === role) &&
43
+ (!heldOnly || s.held_via !== null) &&
44
+ (includePlan || !s.badges.some((b) => b.startsWith("plan:"))) &&
45
+ (includeRoundTrips || !s.round_trip));
46
+ const filters = {
47
+ days,
48
+ min_score: minScore,
49
+ role,
50
+ held_only: heldOnly,
51
+ watched_only: params.get("watchedOnly") !== "false",
52
+ include_plan: includePlan,
53
+ include_round_trips: includeRoundTrips,
54
+ };
55
+ return { ...doc, filters, count: rows.length, truncated: false, signals: rows };
56
+ }
57
+ function clusters(params) {
58
+ const doc = read("signalprism/clusters.json");
59
+ const days = num(params.get("days")) ?? DEFAULT_DAYS;
60
+ const first = cutoff(doc.as_of, days);
61
+ return { ...doc, filters: { days }, clusters: doc.clusters.filter((c) => c.window_end >= first) };
62
+ }
63
+ function ticker(symbol, path, options) {
64
+ const file = `signalprism/ticker/${symbol}.json`;
65
+ if (/^[A-Z0-9.-]+$/.test(symbol) && existsSync(join(DEMO_DIR, file)))
66
+ return read(file);
67
+ if (options.notFound)
68
+ throw new NotFoundError(options.notFound);
69
+ throw new PrismAppError(`${options.app} returned HTTP ${read("signalprism/not-tracked.json").status} for ${path}`);
70
+ }
71
+ /** Answers from the bundled `demo/` captures instead of the network. Any path it doesn't map is an error. */
72
+ export const demoJson = async (_baseUrl, path, options) => {
73
+ const { pathname, searchParams } = new URL(path, "http://demo");
74
+ if (pathname === "/api/health")
75
+ return { ok: true };
76
+ if (pathname === "/api/analysis")
77
+ return read(`folioprism/analysis${searchParams.get("mergeShareClasses") === "1" ? "-merged" : ""}.json`);
78
+ if (pathname === "/api/drift")
79
+ return read("folioprism/drift.json");
80
+ if (pathname === "/api/exposure")
81
+ return exposure(searchParams);
82
+ if (pathname === "/api/mcp/status")
83
+ return { ...read("signalprism/status.json"), stack: "demo" };
84
+ if (pathname === "/api/mcp/signals")
85
+ return signals(searchParams);
86
+ if (pathname === "/api/mcp/clusters")
87
+ return clusters(searchParams);
88
+ const symbol = pathname.match(/^\/api\/mcp\/ticker\/(.+)$/)?.[1];
89
+ if (symbol)
90
+ return ticker(decodeURIComponent(symbol).toUpperCase(), path, options);
91
+ throw new PrismAppError(`not in demo data: ${path}`);
92
+ };
@@ -0,0 +1,42 @@
1
+ import { getJson, NotFoundError, PrismAppError } from "../http.js";
2
+ import { parseDrift } from "./drift-schema.js";
3
+ import { parseExposure } from "./exposure-schema.js";
4
+ import { parseAnalysis } from "./schema.js";
5
+ const APP = "FolioPrism";
6
+ export const ANALYSIS_TIMEOUT_MS = 30_000;
7
+ const DRIFT_NEEDS_NEWER = "folioprism_drift needs FolioPrism 1.4.0 or newer";
8
+ const EXPOSURE_NEEDS_NEWER = "FolioPrism is older than 1.5.0";
9
+ /** A GET-only FolioPrism client that caches each analysis URL for `ttlMs`. */
10
+ export function createFolioPrismClient(baseUrl, { ttlMs = 60_000, timeoutMs = ANALYSIS_TIMEOUT_MS, now = Date.now } = {}) {
11
+ const cache = new Map();
12
+ return {
13
+ analysis(mergeShareClasses) {
14
+ const path = `/api/analysis?mergeShareClasses=${mergeShareClasses ? 1 : 0}`;
15
+ const hit = cache.get(path);
16
+ if (hit && now() - hit.at < ttlMs)
17
+ return hit.value;
18
+ const value = getJson(baseUrl, path, { app: APP, timeoutMs }).then(parseAnalysis);
19
+ value.catch(() => cache.delete(path));
20
+ cache.set(path, { at: now(), value });
21
+ return value;
22
+ },
23
+ async drift() {
24
+ return parseDrift(await getJson(baseUrl, "/api/drift", { app: APP, timeoutMs, notFound: DRIFT_NEEDS_NEWER }));
25
+ },
26
+ async exposure(ticker) {
27
+ const path = `/api/exposure?ticker=${encodeURIComponent(ticker)}&mergeShareClasses=0`;
28
+ try {
29
+ const doc = parseExposure(await getJson(baseUrl, path, { app: APP, timeoutMs, notFound: EXPOSURE_NEEDS_NEWER }));
30
+ const result = doc.results.find((r) => r.ticker.toUpperCase() === ticker.toUpperCase());
31
+ if (!result)
32
+ throw new PrismAppError("FolioPrism returned data in an unexpected shape at results");
33
+ return { result, coveragePct: doc.coveragePct };
34
+ }
35
+ catch (error) {
36
+ if (error instanceof NotFoundError)
37
+ return null;
38
+ throw error;
39
+ }
40
+ },
41
+ };
42
+ }
@@ -0,0 +1,35 @@
1
+ import * as z from "zod";
2
+ import { PrismAppError } from "../http.js";
3
+ /** FolioPrism's /api/drift (v1.4.0). Numbers are decimal strings; percentages only. */
4
+ const Subject = z.object({ ticker: z.string(), pct: z.string(), overCap: z.boolean() });
5
+ const Rule = z.object({
6
+ id: z.number(),
7
+ type: z.enum(["asset_class", "sector", "top10", "single_stock"]),
8
+ label: z.string(),
9
+ status: z.enum(["ok", "breached", "unknown"]),
10
+ reason: z.enum(["stale_prices", "low_coverage", "no_data"]).nullable(),
11
+ base: z.enum(["portfolio", "equity"]),
12
+ target: z.string(),
13
+ actual: z.string(),
14
+ lower: z.string().nullable(),
15
+ upper: z.string(),
16
+ recoveryMargin: z.string(),
17
+ marginClamped: z.boolean(),
18
+ recovering: z.boolean(),
19
+ subjects: z.array(Subject),
20
+ });
21
+ const Drift = z.object({
22
+ asOf: z.string(),
23
+ priceTime: z.string().nullable(),
24
+ coveragePct: z.string().nullable(),
25
+ bandMode: z.enum(["absolute", "relative"]),
26
+ rules: z.array(Rule),
27
+ });
28
+ /** Validate an /api/drift document. */
29
+ export function parseDrift(raw) {
30
+ const result = Drift.safeParse(raw);
31
+ if (result.success)
32
+ return result.data;
33
+ const path = result.error.issues[0].path.join(".") || "(root)";
34
+ throw new PrismAppError(`FolioPrism returned data in an unexpected shape at ${path}`);
35
+ }
@@ -0,0 +1,28 @@
1
+ import * as z from "zod";
2
+ import { PrismAppError } from "../http.js";
3
+ /** FolioPrism's /api/exposure (v1.5.0). Percentages only, as decimal strings. */
4
+ const Result = z.strictObject({
5
+ ticker: z.string(),
6
+ held: z.boolean(),
7
+ totalPct: z.string(),
8
+ directPct: z.string(),
9
+ viaFunds: z.array(z.strictObject({ fund: z.string(), pct: z.string() })),
10
+ inTop50: z.boolean(),
11
+ rank: z.number().int().nullable(),
12
+ mergedWith: z.array(z.string()),
13
+ });
14
+ const Exposure = z.strictObject({
15
+ asOf: z.string(),
16
+ priceTime: z.string().nullable(),
17
+ coveragePct: z.string().nullable(),
18
+ mergeShareClasses: z.boolean(),
19
+ results: z.array(Result),
20
+ });
21
+ /** Validate an /api/exposure document. */
22
+ export function parseExposure(raw) {
23
+ const result = Exposure.safeParse(raw);
24
+ if (result.success)
25
+ return result.data;
26
+ const path = result.error.issues[0].path.join(".") || "(root)";
27
+ throw new PrismAppError(`FolioPrism returned data in an unexpected shape at ${path}`);
28
+ }
@@ -0,0 +1,85 @@
1
+ import * as z from "zod";
2
+ import { PrismAppError } from "../http.js";
3
+ import { dropDollarKeys } from "../privacy.js";
4
+ /**
5
+ * The parts of FolioPrism's /api/analysis the tools use. zod strips undeclared keys, so the
6
+ * only dollar fields kept are the five declared here, which tools show only at detail "full".
7
+ */
8
+ const Pct = z.string();
9
+ const Summary = z.object({
10
+ name: z.string(),
11
+ benchmark: z.string(),
12
+ benchmarkHoldingsAsOf: z.string().nullable(),
13
+ totalCents: z.string(),
14
+ asOf: z.string().nullable(),
15
+ staleTickers: z.array(z.string()),
16
+ unpricedTickers: z.array(z.string()),
17
+ });
18
+ const Holding = z.object({
19
+ ticker: z.string(),
20
+ name: z.string(),
21
+ priceKind: z.string(),
22
+ stale: z.boolean(),
23
+ valueCents: z.string().nullable(),
24
+ });
25
+ const Child = z.object({
26
+ sourceTicker: z.string(),
27
+ sourceName: z.string(),
28
+ fundWeightPct: Pct,
29
+ portfolioPct: Pct,
30
+ valueCents: z.string(),
31
+ });
32
+ const Row = z.object({
33
+ ticker: z.string(),
34
+ name: z.string(),
35
+ portfolioPct: Pct,
36
+ portfolioPctDisplay: Pct,
37
+ valueCents: z.string(),
38
+ children: z.array(Child),
39
+ });
40
+ const CoverageItem = z.object({
41
+ ticker: z.string(),
42
+ source: z.enum(["curated", "yahoo-top10", "imported", "direct"]),
43
+ coveredPct: Pct,
44
+ unavailable: z.boolean(),
45
+ holdingsAsOf: z.string().nullable(),
46
+ });
47
+ const Coverage = z.object({
48
+ lookThroughPct: Pct,
49
+ fundCoveredPct: Pct,
50
+ equityLookThroughPct: Pct.nullable().optional(),
51
+ items: z.array(CoverageItem),
52
+ });
53
+ const Fees = z.object({
54
+ expenseRatioPct: Pct.nullable(),
55
+ feeCents: z.string().nullable(),
56
+ unknownTickers: z.array(z.string()),
57
+ });
58
+ const SectionValue = z.json().transform(dropDollarKeys);
59
+ function section(value) {
60
+ return z.object({ portfolio: value, benchmark: value.nullable() });
61
+ }
62
+ const PrismView = z.object({
63
+ allocation: section(SectionValue),
64
+ styleBox: section(SectionValue),
65
+ sectors: section(SectionValue),
66
+ regions: section(SectionValue),
67
+ valuation: section(SectionValue),
68
+ fees: section(Fees),
69
+ bonds: section(SectionValue),
70
+ });
71
+ const Analysis = z.object({
72
+ summary: Summary,
73
+ holdings: z.array(Holding),
74
+ intersection: z.object({ rows: z.array(Row), coverage: Coverage }),
75
+ prismView: PrismView,
76
+ });
77
+ export const PRISM_VIEW_SECTIONS = PrismView.keyof().options;
78
+ /** Validate an /api/analysis document, keeping only the fields the tools use. */
79
+ export function parseAnalysis(raw) {
80
+ const result = Analysis.safeParse(raw);
81
+ if (result.success)
82
+ return result.data;
83
+ const path = result.error.issues[0].path.join(".") || "(root)";
84
+ throw new PrismAppError(`FolioPrism returned data in an unexpected shape at ${path}`);
85
+ }
package/dist/http.js ADDED
@@ -0,0 +1,54 @@
1
+ /** An error from a Prism app, with a message fit to show the user as-is. */
2
+ export class PrismAppError extends Error {
3
+ unreachable;
4
+ name = "PrismAppError";
5
+ /** True when the app never answered: refused connection or timeout. */
6
+ constructor(message, unreachable = false) {
7
+ super(message);
8
+ this.unreachable = unreachable;
9
+ }
10
+ }
11
+ /** The app answered, but not in the shape this server expects. */
12
+ export class FormatMismatchError extends PrismAppError {
13
+ name = "FormatMismatchError";
14
+ }
15
+ /** The app answered 404 and the caller supplied the message to show for it. */
16
+ export class NotFoundError extends PrismAppError {
17
+ name = "NotFoundError";
18
+ }
19
+ function connectionError(error, url, { app, timeoutMs }) {
20
+ if (error instanceof Error && error.name === "TimeoutError") {
21
+ return new PrismAppError(`${app} on ${url.host} didn't answer within ${timeoutMs / 1000} s`, true);
22
+ }
23
+ return new PrismAppError(`${app} isn't running on ${url.host}`, true);
24
+ }
25
+ /** GET a JSON document from a Prism app over the network. This client never sends any other method. */
26
+ export async function networkJson(baseUrl, path, options) {
27
+ const url = new URL(path, baseUrl);
28
+ let response;
29
+ try {
30
+ response = await fetch(url, { method: "GET", signal: AbortSignal.timeout(options.timeoutMs) });
31
+ }
32
+ catch (error) {
33
+ throw connectionError(error, url, options);
34
+ }
35
+ if (response.status === 404 && options.notFound)
36
+ throw new NotFoundError(options.notFound);
37
+ if (!response.ok)
38
+ throw new PrismAppError(`${options.app} returned HTTP ${response.status} for ${url.pathname}`);
39
+ try {
40
+ return await response.json();
41
+ }
42
+ catch (error) {
43
+ throw error instanceof Error && error.name === "TimeoutError"
44
+ ? connectionError(error, url, options)
45
+ : new PrismAppError(`${options.app} returned invalid JSON`);
46
+ }
47
+ }
48
+ let source = networkJson;
49
+ /** Choose where every request is answered from; the server does this once at start-up. */
50
+ export function setJsonSource(next) {
51
+ source = next;
52
+ }
53
+ /** GET a JSON document from a Prism app, from the network or, in demo mode, from bundled captures. */
54
+ export const getJson = (baseUrl, path, options) => source(baseUrl, path, options);
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { loadConfig } from "./config.js";
4
+ import { createServer } from "./server.js";
5
+ // stdout carries the MCP protocol, so everything else goes to stderr.
6
+ let server;
7
+ try {
8
+ server = createServer(loadConfig());
9
+ }
10
+ catch (error) {
11
+ console.error(error instanceof Error ? error.message : error);
12
+ process.exit(1);
13
+ }
14
+ await server.connect(new StdioServerTransport());
package/dist/log.js ADDED
@@ -0,0 +1,22 @@
1
+ import { appendFileSync, mkdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ /**
4
+ * A call log that appends JSON Lines to `<logDir>/calls.jsonl`. A failed write never
5
+ * fails the tool call; the first failure prints one warning to stderr.
6
+ */
7
+ export function createCallLog(logDir, warn = console.error) {
8
+ const file = join(logDir, "calls.jsonl");
9
+ let warned = false;
10
+ return (entry) => {
11
+ try {
12
+ mkdirSync(logDir, { recursive: true });
13
+ appendFileSync(file, `${JSON.stringify(entry)}\n`);
14
+ }
15
+ catch (error) {
16
+ if (warned)
17
+ return;
18
+ warned = true;
19
+ warn(`prism-mcp: could not write the call log in ${logDir}: ${error.message}`);
20
+ }
21
+ };
22
+ }
@@ -0,0 +1,11 @@
1
+ const DOLLAR_KEY = /(Cents|Usd|usd)$/;
2
+ /** Drop every key ending in Cents, Usd or usd, at any depth. */
3
+ export function dropDollarKeys(value) {
4
+ if (Array.isArray(value))
5
+ return value.map(dropDollarKeys);
6
+ if (value === null || typeof value !== "object")
7
+ return value;
8
+ return Object.fromEntries(Object.entries(value)
9
+ .filter(([key]) => !DOLLAR_KEY.test(key))
10
+ .map(([key, child]) => [key, dropDollarKeys(child)]));
11
+ }
package/dist/server.js ADDED
@@ -0,0 +1,31 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { PACKAGE_ROOT } from "./config.js";
5
+ import { demoJson, demoNow } from "./demo.js";
6
+ import { createFolioPrismClient } from "./folioprism/client.js";
7
+ import { networkJson, setJsonSource } from "./http.js";
8
+ import { createCallLog } from "./log.js";
9
+ import { createSignalPrismClient } from "./signalprism/client.js";
10
+ import { registerFolioPrismTools } from "./tools/folioprism/index.js";
11
+ import { registerTickerOverview } from "./tools/overview/ticker-overview.js";
12
+ import { registerSignalPrismTools } from "./tools/signalprism/index.js";
13
+ import { registerStatus } from "./tools/status.js";
14
+ const PACKAGE_VERSION = JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8")).version;
15
+ /** Build the Prism MCP server with every tool the config leaves on. */
16
+ export function createServer(config, options = {}) {
17
+ setJsonSource(config.demo ? demoJson : networkJson);
18
+ const ctx = {
19
+ config,
20
+ folioprism: createFolioPrismClient(config.apps.folioprism.baseUrl),
21
+ signalprism: createSignalPrismClient(config.apps.signalprism.baseUrl, options.signalprism),
22
+ now: options.now ?? (config.demo ? demoNow : Date.now),
23
+ log: options.log ?? createCallLog(config.logDir),
24
+ };
25
+ const server = new McpServer({ name: "prism-mcp", version: PACKAGE_VERSION });
26
+ registerStatus(server, ctx);
27
+ registerFolioPrismTools(server, ctx);
28
+ registerSignalPrismTools(server, ctx);
29
+ registerTickerOverview(server, ctx);
30
+ return server;
31
+ }
@@ -0,0 +1,34 @@
1
+ import { getJson } from "../http.js";
2
+ import { parseClusters, parseSignals, parseStatus, parseTicker, } from "./schema.js";
3
+ const APP = "SignalPrism";
4
+ export const SIGNALPRISM_TIMEOUT_MS = 30_000;
5
+ /** The path with a query string of only the params that are set, named as SignalPrism names them. */
6
+ export function withQuery(path, params) {
7
+ const query = new URLSearchParams();
8
+ for (const [key, value] of Object.entries(params)) {
9
+ if (value !== undefined)
10
+ query.set(key, String(value));
11
+ }
12
+ return query.size > 0 ? `${path}?${query}` : path;
13
+ }
14
+ /** A GET-only SignalPrism client that caches each URL for `ttlMs`. */
15
+ export function createSignalPrismClient(baseUrl, { ttlMs = 30_000, timeoutMs = SIGNALPRISM_TIMEOUT_MS, now = Date.now, statusTimeoutMs = 5000 } = {}) {
16
+ const cache = new Map();
17
+ function get(path, parse, notFound) {
18
+ const hit = cache.get(path);
19
+ if (hit && now() - hit.at < ttlMs)
20
+ return hit.value;
21
+ const value = getJson(baseUrl, path, { app: APP, timeoutMs, notFound }).then(parse);
22
+ value.catch(() => cache.delete(path));
23
+ cache.set(path, { at: now(), value });
24
+ return value;
25
+ }
26
+ return {
27
+ status: ({ fresh = false } = {}) => fresh
28
+ ? getJson(baseUrl, "/api/mcp/status", { app: APP, timeoutMs: statusTimeoutMs }).then(parseStatus)
29
+ : get("/api/mcp/status", parseStatus),
30
+ signals: (query) => get(withQuery("/api/mcp/signals", { ...query }), parseSignals),
31
+ clusters: (days) => get(withQuery("/api/mcp/clusters", { days }), parseClusters),
32
+ ticker: (symbol) => get(`/api/mcp/ticker/${encodeURIComponent(symbol)}`, parseTicker, `SignalPrism does not track ${symbol} (not in holdings or watchlist)`),
33
+ };
34
+ }