SPB Git

Repository Public Research preview

server.mjs 16.3 KB 212 lines javascript

1#!/usr/bin/env node2/**3 * =============================================================================4 *                  SP BOUCHER | SOFTWARE & RESEARCH5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : LLM API toolkits9 * File             : protocol/mcp/server.mjs10 * Module           : protocol11 * Repository       : https://git.spboucher.ai/llm-api-toolkits12 * Created          : 2026-11-1013 * Last Modified    : 2026-11-1014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: dev@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * research-ledger-mcp — an offline, hash-chained ledger for preregistered research.45 *46 * Everything lives in `.research/` inside one project root. The server never uses the network,47 * never runs a command, and writes nowhere else. Records are appended, never edited.48 */49import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";50import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";51import { realpathSync } from "node:fs";52import { fileURLToPath } from "node:url";53import { z } from "zod";54import { Ledger, LedgerError } from "./lib/ledger.mjs";5556export const VERSION = "1.0.1";5758const out = z.looseObject({});59const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };60const APPEND = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };61const files = (what) => z.array(z.string()).describe(`${what} Paths relative to the project root; each file is hashed (SHA-256) as it is now.`);62const hyps = z.array(z.string()).optional().describe('Hypothesis ids concerned, e.g. ["H1"]. Empty: all hypotheses.');6364const ok = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }], structuredContent: data });65function fail(e) {66  const known = e instanceof LedgerError;67  const error = { code: known ? e.code : "internal_error", message: e?.message ?? String(e), ...(known && e.problem ? { problem: e.problem } : {}), ...(known && e.identical_runs ? { identical_runs: e.identical_runs } : {}) };68  return { isError: true, content: [{ type: "text", text: JSON.stringify({ error }, null, 2) }], structuredContent: { error } };69}7071export function createServer(env = process.env) {72  // The ledger is opened per call so that a wrong root is reported by the tool, not at start-up.73  const ledger = () => new Ledger({ root: env.RESEARCH_LEDGER_ROOT || process.cwd() });74  const server = new McpServer({ name: "research-ledger", version: VERSION, title: "Research ledger" }, {75    capabilities: { tools: {} },76    instructions: "An append-only, hash-chained ledger for a research project, stored in .research/ under the project root. Start every session with status. Order of work: init_project → register_hypothesis → freeze_protocol → (mark_data_access when outcome data are first opened) → runs, decisions, deviations, gates → record_result → export_report. Records are never edited or deleted: correct a mistake by appending a new record that says so. Whether a result is confirmatory or exploratory is derived from the timeline, not declared. Before repeating a costly or non-deterministic step, call check_rerun. Be literal and honest in every field: the ledger is only worth what is written into it.",77  });78  const tool = (name, cfg, fn) => server.registerTool(name, { outputSchema: out, ...cfg }, async (args) => { try { return ok(await fn(args ?? {})); } catch (e) { return fail(e); } });7980  tool("init_project", {81    title: "Start a ledger", annotations: APPEND,82    description: "Create .research/ledger.jsonl in the project root and write its first record. Do this once per project, before anything else. A ledger is never reset.",83    inputSchema: { title: z.string().describe("Project title"), description: z.string().optional().describe("One or two sentences on the question studied"), budget_usd: z.number().min(0).optional().describe("Spending limit for paid calls, in US dollars"), outcome_data: z.string().optional().describe("What counts as outcome data in this project (the data that could reveal the answer)") },84  }, (a) => ledger().init(a));8586  tool("register_hypothesis", {87    title: "Register a hypothesis", annotations: APPEND,88    description: "Record a hypothesis with its test and the rule that will decide it, before the protocol is frozen. Hypotheses are never edited; one registered after the freeze is exploratory unless an amendment made before outcome data covers it.",89    inputSchema: { statement: z.string().describe("What is claimed, in a form that can turn out false"), test: z.string().describe("The analysis that tests it: estimator, sample, specification"), decision_rule: z.string().describe('What result counts as confirmed, stated in advance, e.g. "coefficient > 0, one-sided p < 0.05 with clustered errors"'), direction: z.enum(["positive", "negative", "two_sided", "none"]).optional().describe("Predicted direction (default two_sided)"), role: z.enum(["primary", "secondary"]).optional().describe("Default primary"), id: z.string().optional().describe('Id such as "H1" or "H2a". Default: the next free number.') },90  }, (a) => ledger().registerHypothesis(a));9192  tool("freeze_protocol", {93    title: "Freeze the protocol", annotations: APPEND,94    description: "Fix the protocol: hash every listed file and the registered hypotheses into one root hash. Do this before outcome data are opened. Refuses to freeze twice; later changes go through amend_protocol.",95    inputSchema: { files: files("Protocol documents and analysis code that define the study."), note: z.string().optional() },96  }, (a) => ledger().freeze(a));9798  tool("verify_protocol", {99    title: "Check the frozen files", annotations: READ,100    description: "Re-hash the files of the protocol version in force and report exactly which ones changed, went missing, or were renamed. Read-only.",101    inputSchema: {},102  }, () => ledger().verifyProtocol());103104  tool("amend_protocol", {105    title: "Amend the protocol", annotations: APPEND,106    description: "Record a change to a frozen protocol as a new linked version, with the reason and whether outcome data had been seen. An amendment after data makes later results for the affected hypotheses exploratory.",107    inputSchema: { files: files("The complete file list of the new version (not only the changed files)."), reason: z.string().describe("Why the protocol changes"), data_seen: z.boolean().describe("Had outcome data been seen when this change was decided? Answer truthfully; the ledger overrides a false 'no' when it already records data access."), affects: hyps },108  }, (a) => ledger().amend(a));109110  tool("mark_data_access", {111    title: "Record data access", annotations: APPEND,112    description: "Record the moment data are first opened. With outcome_data true (default) this is the line between confirmatory and exploratory work: anything frozen afterwards cannot be confirmatory.",113    inputSchema: { description: z.string().describe("Which data, and what was looked at"), outcome_data: z.boolean().optional().describe("False for data that cannot reveal the answer (e.g. covariates only, a pilot on other data)") },114  }, (a) => ledger().markDataAccess(a));115116  tool("log_decision", {117    title: "Record a decision", annotations: APPEND,118    description: "Record an analytic or design decision: the question, the options considered, the choice and why. Numbered D-01, D-02… in order of writing. Say honestly whether it was made before or after seeing outcome data.",119    inputSchema: { question: z.string(), options: z.array(z.string()).describe("At least two options that were really considered"), choice: z.string(), rationale: z.string(), timing: z.enum(["before_outcome_data", "after_outcome_data"]) },120  }, (a) => ledger().logDecision(a));121122  tool("log_deviation", {123    title: "Record a deviation", annotations: APPEND,124    description: "Record a departure from the frozen protocol: what it said, what was done, why, and what that does to confirmatory status. Numbered V-01, V-02…",125    inputSchema: { protocol_said: z.string(), done: z.string(), reason: z.string(), impact: z.enum(["none", "minor", "exploratory"]).describe("none: cannot affect the result. minor: reported as confirmatory with deviations. exploratory: the affected results lose confirmatory status."), hypotheses: hyps },126  }, (a) => ledger().logDeviation(a));127128  tool("open_gate", {129    title: "Open a gate", annotations: APPEND,130    description: "Open a go / no-go review with its criteria written down first, so the bar is on record before the evidence is.",131    inputSchema: { name: z.string().describe('Short name, e.g. "A: data sufficiency"'), criteria: z.array(z.string()).describe("Checkable criteria, each one able to fail"), purpose: z.string().optional() },132  }, (a) => ledger().openGate(a));133134  tool("close_gate", {135    title: "Close a gate", annotations: APPEND,136    description: "Close an open gate as go, no_go or conditional, with the evidence examined against each criterion. No-go is a legitimate result.",137    inputSchema: { name: z.string(), outcome: z.enum(["go", "no_go", "conditional"]), evidence: z.array(z.string()).describe("What was observed, criterion by criterion, with numbers"), conditions: z.array(z.string()).optional().describe("Required when the outcome is conditional"), notes: z.string().optional() },138  }, (a) => ledger().closeGate(a));139140  tool("check_rerun", {141    title: "Before repeating a run", annotations: READ,142    description: "Ask whether an identical run (same command, code, inputs and seed) is already on record, and whether it was marked expensive. Call this before any costly or non-deterministic step. Read-only.",143    inputSchema: { command: z.string(), code_files: files("Code the run executes.").optional(), input_files: files("Inputs the run reads.").optional(), seed: z.union([z.number(), z.string()]).optional() },144  }, (a) => ledger().checkRerun(a));145146  tool("register_run", {147    title: "Record a run", annotations: APPEND,148    description: "Record a finished run: command, hashes of code, inputs and outputs, seed, environment, times. The server does not execute anything. Mark expensive for paid, slow or non-deterministic steps; an identical expensive run is then refused unless rerun_reason is given.",149    inputSchema: { name: z.string(), command: z.string().describe("The command as it was run"), code_files: files("Code the run executed.").optional(), input_files: files("Inputs the run read.").optional(), output_files: files("Outputs the run wrote.").optional(), seed: z.union([z.number(), z.string()]).optional(), status: z.enum(["completed", "failed"]).optional(), expensive: z.boolean().optional().describe("True: do not repeat this run"), deterministic: z.boolean().optional().describe("False when the same inputs can give different outputs (sampling, model calls)"), started_at: z.string().optional().describe("ISO date-time"), ended_at: z.string().optional().describe("ISO date-time"), environment: z.string().optional().describe("Interpreter and key package versions, machine"), rerun_reason: z.string().optional().describe("Why an identical expensive run is being repeated"), notes: z.string().optional() },150  }, (a) => ledger().registerRun(a));151152  tool("record_spend", {153    title: "Record spending", annotations: APPEND,154    description: "Record the cost of paid calls (model APIs, data, compute) and return the running total and what is left of the budget.",155    inputSchema: { provider: z.string(), purpose: z.string().describe("What the money bought, in the project's terms"), cost_usd: z.number().min(0), model: z.string().optional(), input_tokens: z.number().int().min(0).optional(), output_tokens: z.number().int().min(0).optional(), run_id: z.string().optional().describe('Run this spending belongs to, e.g. "R-02"') },156  }, (a) => ledger().recordSpend(a));157158  tool("spend_report", {159    title: "Spending so far", annotations: READ,160    description: "Totals by provider, model and purpose, with the budget and what remains. Amounts are summed in millionths of a dollar, so totals are exact. Read-only.",161    inputSchema: {},162  }, () => ledger().spendReport());163164  tool("set_budget", {165    title: "Change the budget", annotations: APPEND,166    description: "Set or change the spending limit, with the reason. The previous limit stays on record.",167    inputSchema: { budget_usd: z.number().min(0), reason: z.string() },168  }, (a) => ledger().setBudget(a));169170  tool("record_result", {171    title: "Record a result", annotations: APPEND,172    description: "Record the outcome for a hypothesis: estimate, uncertainty and verdict. The ledger derives confirmatory / exploratory status itself from the freeze timeline, amendments, deviations and whether the frozen files are intact. Record null and inconclusive results exactly like positive ones.",173    inputSchema: { hypothesis: z.string().describe('Hypothesis id, e.g. "H1"'), verdict: z.enum(["confirmed", "not_confirmed", "inconclusive"]).describe("Against the decision rule registered in advance"), estimate: z.union([z.number(), z.string()]).optional(), uncertainty: z.string().optional().describe('Standard error, interval or test statistic, e.g. "95% CI [0.02, 0.19]"'), run_id: z.string().optional(), notes: z.string().optional() },174  }, (a) => ledger().recordResult(a));175176  tool("log_question", {177    title: "Note an open question", annotations: APPEND,178    description: "Note something unresolved so that a later session sees it in status. Numbered Q-01, Q-02…",179    inputSchema: { question: z.string() },180  }, (a) => ledger().logQuestion(a));181182  tool("resolve_question", {183    title: "Resolve an open question", annotations: APPEND,184    description: "Record the answer to an open question. The question stays in the ledger; it only leaves the open list.",185    inputSchema: { id: z.string().describe('e.g. "Q-01"'), answer: z.string() },186  }, (a) => ledger().resolveQuestion(a));187188  tool("status", {189    title: "Where the project stands", annotations: READ,190    description: "Everything needed to resume in a new session: protocol state and integrity, hypotheses and results, gates, open questions, spending, the latest records and suggested next steps. Read-only; call it first.",191    inputSchema: {},192  }, () => ledger().status());193194  tool("export_report", {195    title: "Transparency report", annotations: { ...APPEND, idempotentHint: true },196    description: "Build the transparency report (Markdown and JSON): protocol versions, every hypothesis with its result and status, decisions, deviations, gates, runs, spending. With write true, also saves both under .research/reports/.",197    inputSchema: { write: z.boolean().optional().describe("Save the report files under .research/reports/ (default false: return only)") },198  }, (a) => ledger().exportReport(a));199200  tool("verify_ledger", {201    title: "Verify the ledger", annotations: READ,202    description: "Re-compute the hash chain and report the first record that was edited, deleted, reordered or truncated. Read-only. States plainly what the chain does and does not prove.",203    inputSchema: {},204  }, () => ledger().verifyLedger());205206  return server;207}208209// Compare real paths: the server may be started through a symlink (e.g. /var → /private/var on macOS).210const isMain = (() => { try { return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); } catch { return false; } })();211if (isMain) await createServer().connect(new StdioServerTransport());212
Files main
Menu

Theme