Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: enforce every tool's schema required fields in the MCP dispatcher (#303)

Brenno Ferrari57b38bad2804
diff --git a/.claude/scripts/lib/mcp-server.ts b/.claude/scripts/lib/mcp-server.ts
index a5d4595..a34d304 100644
--- a/.claude/scripts/lib/mcp-server.ts
+++ b/.claude/scripts/lib/mcp-server.ts
@@ -104,6 +104,35 @@ const text = (s: string): { content: { type: "text"; text: string }[] } => ({
content: [{ type: "text", text: s }],
});
+/** How each tool's refusal opens, so a refused call reads like that tool's own. */
+const REFUSAL_VERB: Readonly<Record<string, string>> = {
+ record_work: "Not recorded",
+ remember: "Not remembered",
+};
+
+/**
+ * The first field a call is missing among those its tool's schema marks
+ * `required`, or null. `required` is advisory to a client: one that does not
+ * validate against the schema sends the call anyway, and each handler used to
+ * meet the gap its own way — a `<date>-undefined.md` note, a title of `42`, a
+ * search for "". Checked here, against the same TOOLS that `tools/list`
+ * serves, so a new tool or a new required field is covered without new code.
+ * A string-typed field must be a non-empty string; any other type, present.
+ */
+export function missingRequired(tool: string | undefined, args: Record<string, unknown>): string | null {
+ const schema = TOOLS.find((t) => t.name === tool)?.inputSchema as
+ | { required?: unknown; properties?: Record<string, { type?: unknown }> }
+ | undefined;
+ if (!schema || !Array.isArray(schema.required)) return null;
+ for (const field of schema.required) {
+ if (typeof field !== "string") continue;
+ const v = args[field];
+ const isString = schema.properties?.[field]?.type === "string";
+ if (isString ? typeof v !== "string" || v.trim() === "" : v === undefined || v === null) return field;
+ }
+ return null;
+}
+
/**
* Re-index after a write.
*
@@ -554,16 +583,9 @@ export function createHandlers(deps: ServerDeps): Handlers {
}
function callRecordWork(args: Record<string, unknown>): string {
- // `required` in the tool schema is advisory: a client that does not
- // validate against it sends the call without the field, and a missing
- // title used to become a `<date>-undefined.md` note with an empty H1.
- for (const field of ["title", "summary"] as const) {
- const v = args[field];
- if (typeof v !== "string" || v.trim() === "") {
- audit("refused", { tool: "record_work", reason: `missing ${field}` });
- return `Not recorded: \`${field}\` is required and must be a non-empty string.`;
- }
- }
+ // A missing title or summary never reaches here: the dispatcher refuses
+ // every call that lacks a field its schema marks `required`.
+ //
// A field carrying tool-call framing means the call's serialization broke,
// not that the author wrote something odd. Refuse: writing it produces a
// corrupted note whose damage is invisible until a human reads the rendered
@@ -853,6 +875,14 @@ export function createHandlers(deps: ServerDeps): Handlers {
await session.identityReady();
const p = (params ?? {}) as { name?: string; arguments?: Record<string, unknown> };
const args = p.arguments ?? {};
+ const missing = missingRequired(p.name, args);
+ if (missing) {
+ audit("refused", { tool: p.name, reason: `missing ${missing}` });
+ return session.ok(
+ id,
+ text(`${REFUSAL_VERB[p.name ?? ""] ?? "Not run"}: \`${missing}\` is required and must be a non-empty string.`),
+ );
+ }
switch (p.name) {
case "search":
return session.ok(id, text(await callSearch(args)));
diff --git a/.claude/scripts/tests/mcp-refusal-audit.test.ts b/.claude/scripts/tests/mcp-refusal-audit.test.ts
index 23345fa..705a018 100644
--- a/.claude/scripts/tests/mcp-refusal-audit.test.ts
+++ b/.claude/scripts/tests/mcp-refusal-audit.test.ts
@@ -66,7 +66,9 @@ describe("a refused call is auditable", () => {
const dir = mkdtempSync(join(tmpdir(), "refuse-"));
try {
const { call, logged } = harness(dir);
- await call("remember", CORRUPTED);
+ // Every required field present, so the call reaches the markup check
+ // rather than the dispatcher's missing-field refusal.
+ await call("remember", { ...CORRUPTED, confidence: "inferred" });
const refusals = logged.filter((l) => l.action === "refused");
assert.equal(refusals.length, 1, "a refusal that logs nothing is a loop nobody can diagnose");
@@ -87,11 +89,14 @@ describe("a refused call is auditable", () => {
const dir = mkdtempSync(join(tmpdir(), "refuse-"));
try {
const { call, logged } = harness(dir);
- await call("record_work", { ...CORRUPTED, folder: "brain" });
+ await call("record_work", { ...CORRUPTED, summary: "a summary", folder: "brain" });
const refusals = logged.filter((l) => l.action === "refused");
assert.equal(refusals.length, 1);
assert.equal(refusals[0]!.detail["tool"], "record_work");
+ // Pinned: without `summary` this was refused as a missing field and
+ // never reached the markup check it exists to cover.
+ assert.equal(refusals[0]!.detail["reason"], "tool-call markup");
} finally {
rmTemp(dir);
}
diff --git a/.claude/scripts/tests/mcp-required.test.ts b/.claude/scripts/tests/mcp-required.test.ts
new file mode 100644
index 0000000..cdad713
--- /dev/null
+++ b/.claude/scripts/tests/mcp-required.test.ts
@@ -0,0 +1,134 @@
+/**
+ * Every tool's schema `required` fields are enforced in the dispatcher.
+ *
+ * `required` is advisory: a client that does not validate against the schema
+ * sends the call anyway, and each handler used to meet the gap its own way —
+ * `record_work` wrote `<date>-undefined.md`, `remember` accepted a title of
+ * `42`, `search`/`expand`/`reason` ran on "". The cases below are generated
+ * from TOOLS, the list `tools/list` serves, so a new tool or a new required
+ * field is covered without a new test.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { createHandlers, missingRequired } from "../lib/mcp-server.ts";
+import { TOOLS } from "../lib/mcp-tools.ts";
+
+import { rmTemp } from "./_helpers.ts";
+
+interface Logged {
+ readonly action: string;
+ readonly detail: Record<string, unknown>;
+}
+
+function harness(vaultRoot: string) {
+ const logged: Logged[] = [];
+ const session = {
+ roots: [{ uri: "file:///elsewhere/some-project", name: "some-project" }],
+ identityReady: async () => {},
+ ok: (_id: unknown, r: unknown) => r,
+ error: (_id: unknown, e: unknown) => e,
+ fail: (_id: unknown, e: unknown) => e,
+ };
+ const handlers = createHandlers({
+ ctx: { vaultRoot, memoryRoot: "memories", qmdIndex: null },
+ policy: { roots: ["brain"], neverExpose: new Set(), source: "manifest", memoryRoot: "memories" },
+ session,
+ qmd: () => ({}),
+ audit: (action: string, detail: Record<string, unknown> = {}) => logged.push({ action, detail }),
+ now: () => new Date(2026, 6, 26),
+ reindex: () => true,
+ } as never);
+ const call = async (name: string, args: Record<string, unknown>): Promise<string> => {
+ const r = (await (handlers as never as Record<string, (id: number, p: unknown) => Promise<unknown>>)[
+ "tools/call"
+ ]!(1, { name, arguments: args })) as { content?: { text?: string }[] };
+ return r?.content?.[0]?.text ?? JSON.stringify(r);
+ };
+ return { call, logged };
+}
+
+type Schema = { required?: string[]; properties?: Record<string, { type?: string; enum?: unknown[] }> };
+
+/** A call that satisfies every required field of `tool`'s schema. */
+function completeArgs(schema: Schema): Record<string, unknown> {
+ const args: Record<string, unknown> = {};
+ for (const f of schema.required ?? []) {
+ const p = schema.properties?.[f];
+ args[f] = p?.enum?.[0] ?? (p?.type === "string" ? `a ${f}` : 1);
+ }
+ return args;
+}
+
+const REFUSAL = /^Not (recorded|remembered|run): `([^`]+)` is required and must be a non-empty string\.$/;
+
+const withRequired = TOOLS.filter((t) => ((t.inputSchema as Schema).required ?? []).length > 0);
+
+describe("the dispatcher refuses a call missing a required field", () => {
+ test("the tools that declare required fields are all covered", () => {
+ assert.deepEqual(
+ withRequired.map((t) => t.name).sort(),
+ ["expand", "reason", "record_work", "remember", "search"],
+ );
+ });
+
+ for (const tool of withRequired) {
+ const schema = tool.inputSchema as Schema;
+ for (const field of schema.required ?? []) {
+ const bad: [string, unknown][] = [
+ ["absent", undefined],
+ ["empty", ""],
+ ["whitespace", " "],
+ ["non-string", 42],
+ ];
+ for (const [label, value] of bad) {
+ test(`${tool.name} with ${field} ${label} → refused, audited, handler not reached`, async () => {
+ const dir = mkdtempSync(join(tmpdir(), "mcp-required-"));
+ try {
+ mkdirSync(join(dir, "brain"));
+ const { call, logged } = harness(dir);
+ const args = completeArgs(schema);
+ if (value === undefined) delete args[field];
+ else args[field] = value;
+ const out = await call(tool.name, args);
+ const m = REFUSAL.exec(out);
+ assert.ok(m, `expected the dispatcher's refusal, got: ${out}`);
+ assert.equal(m[2], field);
+ const refusals = logged.filter((l) => l.action === "refused");
+ assert.equal(refusals.length, 1);
+ assert.deepEqual(refusals[0]!.detail, { tool: tool.name, reason: `missing ${field}` });
+ } finally {
+ rmTemp(dir);
+ }
+ });
+ }
+ }
+ }
+
+ test("remember with a non-string title is refused, not stringified", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "mcp-required-"));
+ try {
+ const { call } = harness(dir);
+ const out = await call("remember", { title: 42, body: "x".repeat(200), confidence: "verified" });
+ assert.equal(out, "Not remembered: `title` is required and must be a non-empty string.");
+ } finally {
+ rmTemp(dir);
+ }
+ });
+
+ test("a call with every required field present passes the check", () => {
+ for (const tool of withRequired) {
+ assert.equal(missingRequired(tool.name, completeArgs(tool.inputSchema as Schema)), null, tool.name);
+ }
+ });
+
+ test("an unknown tool or one with no required list is not checked here", () => {
+ assert.equal(missingRequired("health", {}), null);
+ assert.equal(missingRequired("no-such-tool", {}), null);
+ assert.equal(missingRequired(undefined, {}), null);
+ });
+});
diff --git a/.claude/scripts/tests/om-mcp.integration.test.ts b/.claude/scripts/tests/om-mcp.integration.test.ts
index 424027e..8c22ba6 100644
--- a/.claude/scripts/tests/om-mcp.integration.test.ts
+++ b/.claude/scripts/tests/om-mcp.integration.test.ts
@@ -179,10 +179,11 @@ describe("the om server on the wire", () => {
test("reason refuses an empty question without spawning anything", async () => {
// This suite must never hand `reason` a real question — that would start a
// second Claude session from a unit test. The empty-question path is the one
- // refusal reachable without spawning, and it proves the handler is wired.
+ // refusal reachable without spawning. Since #300 the dispatcher refuses it,
+ // from the schema's `required`, before the handler is reached.
const out = textOf(await call("tools/call", { name: "reason", arguments: { question: " " } }));
assert.match(out, /Not run:/);
- assert.match(out, /no question/);
+ assert.match(out, /`question` is required/);
});
test("the resource listing honours the policy — work/ never appears", async () => {