Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Respect MCP audit request lifetime (PRD-9856) (#7448)

Andrew Mikofalvy505743ad2a5d
diff --git a/.changeset/audit-request-lifetime.md b/.changeset/audit-request-lifetime.md
new file mode 100644
index 000000000..bc2e28f2f
--- /dev/null
+++ b/.changeset/audit-request-lifetime.md
@@ -0,0 +1,6 @@
+---
+'@inkeep/open-knowledge': patch
+'@inkeep/open-knowledge-server': patch
+---
+
+Let large MCP audit and project-wide lint scans run beyond 30 seconds. Client timeouts still apply, with a 120-second limit for `ok mcp --port` and Node's 300-second response-header deadline; narrow the scan path when needed.
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index da80463b8..7d5776ef3 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -38,6 +38,8 @@ To point an MCP client at this server, locally or over a tunnel from another mac
## Audit scopes and complete results
+Large `audit` and project-wide `lint` scans can exceed the MCP client's request timeout; raise the client's timeout when possible, or narrow `path` to a file or folder and retry. Node's HTTP transport permits up to 300 seconds for response headers or between body chunks; `ok mcp --port` additionally has a fixed 120-second request limit that cannot be increased through the CLI.
+
The `path` scope for `audit` and project-wide `lint` selects an existing file or directory first. If a document stem without `.md` or `.mdx` does not exist, OpenKnowledge tries `.mdx` before `.md`; an explicitly supplied document extension must exist as written. An unknown scope returns a not-found error naming the path and how to correct it. An existing empty or ignored scope reports zero documents checked and an informational warning, rather than implying the content passed validation. The CLI equivalents, `ok audit` and `ok lint`, share these path-resolution rules: unknown scopes exit 1 (before any `--fix` write), while valid zero-document scopes exit 0. `audit`, project-wide `lint` and server-backed `ok audit` refuse hidden-segment scopes: zero documents are checked and the refusal is an ordinary warning, not the informational empty-scope one (`ok audit` exits 0). Headless `ok lint` checks them when explicitly named.
Narrowing `path` reduces competing files, but does not lift per-file caps. Use `lint({ document: "guides/intro" })` for all document-lint findings, and `links({ kind: "dead", sourceDocuments: ["guides/intro"] })` for raw unresolved links from that document. Project-tree OKF findings in MCP audit results remain capped. Diagnostic totals always cover the full scan.
diff --git a/packages/server/src/mcp/tools/audit.test.ts b/packages/server/src/mcp/tools/audit.test.ts
index 501f86966..5885a1216 100644
--- a/packages/server/src/mcp/tools/audit.test.ts
+++ b/packages/server/src/mcp/tools/audit.test.ts
@@ -1,11 +1,16 @@
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import type { AuditDeps } from './audit.ts';
import { DESCRIPTION, register } from './audit.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
+import { register as registerLint } from './lint.ts';
import type { ServerInstance } from './shared.ts';
import {
AUDIT_FILE_CAP,
@@ -30,7 +35,7 @@ interface RegisteredTool {
name: string;
description: string;
annotations?: Record<string, unknown>;
- handler: (args: AuditHandlerArgs) => Promise<ToolResult>;
+ handler: (args: AuditHandlerArgs, signal?: AbortSignal) => Promise<ToolResult>;
}
function createFakeServer() {
@@ -39,13 +44,13 @@ function createFakeServer() {
registerTool(
name: string,
cfg: { description?: string; annotations?: Record<string, unknown> },
- handler: (args: AuditHandlerArgs) => Promise<ToolResult>,
+ handler: (args: AuditHandlerArgs, extra: { signal: AbortSignal }) => Promise<ToolResult>,
) {
registered = {
name,
description: cfg.description ?? '',
annotations: cfg.annotations,
- handler,
+ handler: (args, signal = new AbortController().signal) => handler(args, { signal }),
};
},
} as unknown as ServerInstance;
@@ -282,6 +287,61 @@ describe('audit — registration + DESCRIPTION', () => {
});
});
+describe('audit request lifetime', () => {
+ test('honors the MCP request cancellation signal', async () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl, tmpDir));
+ const signal = AbortSignal.abort(new DOMException('Caller deadline expired', 'TimeoutError'));
+
+ const result = await getTool().handler({}, signal);
+
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toContain('Caller deadline expired');
+ });
+
+ test('real MCP project scans can finish after the old 30-second HTTP deadline', async () => {
+ const slowServer = await startFetchTestServer({
+ async fetch() {
+ await delay(31_000);
+ return Response.json({
+ ok: true,
+ files: [],
+ fileCount: 1,
+ errorCount: 0,
+ warningCount: 0,
+ warnings: [],
+ });
+ },
+ });
+ const mcp = new McpServer({ name: 'audit-deadline-test', version: '1.0.0' });
+ const client = new Client({ name: 'audit-deadline-client', version: '1.0.0' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ try {
+ register(mcp, makeDeps(`http://127.0.0.1:${slowServer.port}`, tmpDir));
+ registerLint(mcp, makeDeps(`http://127.0.0.1:${slowServer.port}`, tmpDir));
+ await Promise.all([mcp.connect(serverTransport), client.connect(clientTransport)]);
+
+ const results = await Promise.all(
+ ['audit', 'lint'].map((name) =>
+ client.callTool({ name, arguments: {} }, undefined, { timeout: 45_000 }),
+ ),
+ );
+
+ for (const result of results) {
+ expect(result.isError ?? false).toBe(false);
+ expect(result.structuredContent).toMatchObject({
+ fileCount: 1,
+ errorCount: 0,
+ warningCount: 0,
+ });
+ }
+ } finally {
+ slowServer.stop();
+ await Promise.all([client.close(), mcp.close()]);
+ }
+ }, 60_000);
+});
+
describe('audit — unified project audit', () => {
test('no args hits /api/audit and returns both validator sources tagged', async () => {
const { server, getTool } = createFakeServer();
diff --git a/packages/server/src/mcp/tools/audit.ts b/packages/server/src/mcp/tools/audit.ts
index 2ac22864b..cb36ef640 100644
--- a/packages/server/src/mcp/tools/audit.ts
+++ b/packages/server/src/mcp/tools/audit.ts
@@ -29,6 +29,7 @@ export const DESCRIPTION = [
'ran names selected `markdownlint`, `frontmatter`, `okf`, `links`. A family absent from `ran` was not checked. A selected family remains in ran if degraded; warnings explain why and it may still have contributed findings. okf covers document and project-tree OKF checks here.',
"Broken links are reported under the source doc. Default-on validation.suppressLogLinkAdvisories omits links inside lowercase log.md/log.mdx at any depth; LOG.md is ordinary. brokenLinkSuppression reports reason reserved-log-policy and count without paths/hrefs. Logs are append-only history: never rewrite old entries to clear links. links({kind:'dead'}) reads raw state.",
'Diagnostics carry source, code, message, 0-based LSP range (link columns approximate) and severity. Broken links default to warning; validation.links can raise/hide them. Only problematic files are listed; fileCount/errorCount/warningCount reflect full scan. Output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow runtime hints for document lint and raw dead links; project-tree OKF findings remain capped.',
+ 'Large project scans can exceed host or transport timeouts. If a scan times out, narrow `path` to a file or folder and retry.',
'Nothing is modified. Auto-fix document lint with lint({document,fix:true}); fix broken links with edit/write.',
].join('\n');
@@ -123,7 +124,7 @@ export function register(server: ServerInstance, deps: AuditDeps): void {
idempotentHint: true,
},
},
- async (args: AuditArgs) => {
+ async (args: AuditArgs, { signal }) => {
const context = await resolveProjectServerContext(
deps.resolveCwd,
deps.config,
@@ -133,14 +134,14 @@ export function register(server: ServerInstance, deps: AuditDeps): void {
if (!context.ok) return textResult(`Error: ${context.error}`, true);
const { cwd, url } = context;
if (!url) return textResult(hocuspocusNotRunningError(), true);
- return runAudit(args.path, url, cwd);
+ return runAudit(args.path, url, cwd, signal);
},
);
}
-async function runAudit(path: string | undefined, url: string, cwd: string) {
+async function runAudit(path: string | undefined, url: string, cwd: string, signal: AbortSignal) {
const query = path ? `?path=${encodeURIComponent(path)}` : '';
- const result = await httpGet(url, `/api/audit${query}`);
+ const result = await httpGet(url, `/api/audit${query}`, signal);
if (!result.ok) return textResult(`Error: ${String(result.error)}`, true);
const { ok: _ok, ...rest } = result;
const data = rest as AuditResponsePayload;
diff --git a/packages/server/src/mcp/tools/lint.test.ts b/packages/server/src/mcp/tools/lint.test.ts
index 652a7394f..b9ca2b2ef 100644
--- a/packages/server/src/mcp/tools/lint.test.ts
+++ b/packages/server/src/mcp/tools/lint.test.ts
@@ -26,7 +26,7 @@ interface RegisteredTool {
name: string;
description: string;
annotations?: Record<string, unknown>;
- handler: (args: LintHandlerArgs) => Promise<ToolResult>;
+ handler: (args: LintHandlerArgs, signal?: AbortSignal) => Promise<ToolResult>;
}
function createFakeServer() {
@@ -35,13 +35,13 @@ function createFakeServer() {
registerTool(
name: string,
cfg: { description?: string; annotations?: Record<string, unknown> },
- handler: (args: LintHandlerArgs) => Promise<ToolResult>,
+ handler: (args: LintHandlerArgs, extra: { signal: AbortSignal }) => Promise<ToolResult>,
) {
registered = {
name,
description: cfg.description ?? '',
annotations: cfg.annotations,
- handler,
+ handler: (args, signal = new AbortController().signal) => handler(args, { signal }),
};
},
} as unknown as ServerInstance;
@@ -58,6 +58,17 @@ function makeDeps(serverUrl: string | undefined, cwdDir: string): LintDeps {
return { serverUrl, config: BASE_CONFIG, resolveCwd: async () => cwdDir };
}
+test('project-wide lint honors the MCP request cancellation signal', async () => {
+ const { server, getTool } = createFakeServer();
+ register(server, makeDeps(baseUrl, tmpDir));
+ const signal = AbortSignal.abort(new DOMException('Caller deadline expired', 'TimeoutError'));
+
+ const result = await getTool().handler({}, signal);
+
+ expect(result.isError).toBe(true);
+ expect(result.content[0]?.text).toContain('Caller deadline expired');
+});
+
let testServer: FetchTestServer;
let baseUrl: string;
let tmpDir: string;
diff --git a/packages/server/src/mcp/tools/lint.ts b/packages/server/src/mcp/tools/lint.ts
index 77fe150e8..526271664 100644
--- a/packages/server/src/mcp/tools/lint.ts
+++ b/packages/server/src/mcp/tools/lint.ts
@@ -49,6 +49,7 @@ export const DESCRIPTION = [
'ran lists selected `markdownlint`, `frontmatter` and document-level `okf` families. A family absent from `ran` was not checked. Project-tree OKF checks and link validation run only through audit.',
'Findings carry source, code, message, 0-based LSP range and severity; only problematic files are listed. Counts reflect the full scan. Project output is capped at 10 files × 10 diagnostics each and project-wide at 10 warnings; omittedWarningCount reports dropped warnings. Narrow path reduces competing files; per-file caps still apply. Follow truncation recovery text.',
'Configure lint in Settings → Plugins and native .markdownlint.* rules.',
+ 'If a project-wide scan times out, narrow `path` to a file or folder and retry.',
].join('\n');
export const LINT_WARNINGS_DESCRIPTION =
@@ -203,7 +204,7 @@ export function register(server: ServerInstance, deps: LintDeps): void {
idempotentHint: true,
},
},
- async (args: LintArgs) => {
+ async (args: LintArgs, { signal }) => {
const context = await resolveProjectServerContext(
deps.resolveCwd,
deps.config,
@@ -226,7 +227,7 @@ export function register(server: ServerInstance, deps: LintDeps): void {
return args.document !== undefined
? lintSingleDoc(args.document, url, cwd)
- : lintAudit(args.path, url, cwd);
+ : lintAudit(args.path, url, cwd, signal);
},
);
}
@@ -374,9 +375,9 @@ async function lintSingleDoc(document: string, url: string, cwd: string) {
return textPlusStructured(textLines.join('\n'), structured);
}
-async function lintAudit(path: string | undefined, url: string, cwd: string) {
+async function lintAudit(path: string | undefined, url: string, cwd: string, signal: AbortSignal) {
const query = path ? `?path=${encodeURIComponent(path)}` : '';
- const result = await httpGet(url, `/api/lint/audit${query}`);
+ const result = await httpGet(url, `/api/lint/audit${query}`, signal);
if (!result.ok) return textResult(`Error: ${String(result.error)}`, true);
const { ok: _ok, ...rest } = result;
const data = rest as LintAuditPayload;
diff --git a/packages/server/src/mcp/tools/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
index 7c4cc9940..95e53abf3 100644
--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts
+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
@@ -48,8 +48,18 @@ function captureRegistration<TDeps>(
): Captured {
let captured: Captured | null = null;
const server = {
- registerTool(_name: string, cfg: Captured['cfg'], handler: AnyHandler) {
- captured = { cfg, handler };
+ registerTool(
+ _name: string,
+ cfg: Captured['cfg'],
+ handler: (
+ args: Record<string, unknown>,
+ extra: { signal: AbortSignal },
+ ) => Promise<ToolResult>,
+ ) {
+ captured = {
+ cfg,
+ handler: (args) => handler(args, { signal: new AbortController().signal }),
+ };
},
tool() {
throw new Error('not used');
diff --git a/packages/server/src/mcp/tools/session-capacity-refusal.test.ts b/packages/server/src/mcp/tools/session-capacity-refusal.test.ts
index 6ce44f508..3f0266b6d 100644
--- a/packages/server/src/mcp/tools/session-capacity-refusal.test.ts
+++ b/packages/server/src/mcp/tools/session-capacity-refusal.test.ts
@@ -121,8 +121,15 @@ describe('MCP write paths relaying an agent-session capacity refusal', () => {
['lint', registerLint],
] as const) {
const server = {
- registerTool(_name: string, _cfg: unknown, toolHandler: Handler) {
- handlers.set(name, toolHandler);
+ registerTool(
+ _name: string,
+ _cfg: unknown,
+ toolHandler: (
+ args: Record<string, unknown>,
+ extra: { signal: AbortSignal },
+ ) => Promise<ToolResult>,
+ ) {
+ handlers.set(name, (args) => toolHandler(args, { signal: new AbortController().signal }));
},
} as unknown as ServerInstance;
register(server, deps);
diff --git a/packages/server/src/mcp/tools/shared.test.ts b/packages/server/src/mcp/tools/shared.test.ts
index ed184d702..405acc080 100644
--- a/packages/server/src/mcp/tools/shared.test.ts
+++ b/packages/server/src/mcp/tools/shared.test.ts
@@ -562,6 +562,20 @@ describe('httpPost', () => {
});
describe('a request that runs out of time', () => {
+ test.each(['UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT'])(
+ 'recognizes a fetch transport timeout: %s',
+ async (code) => {
+ const cause = Object.assign(new Error('Transport deadline expired'), { code });
+ vi.stubGlobal('fetch', () => Promise.reject(new TypeError('fetch failed', { cause })));
+ try {
+ const result = await httpGet('http://localhost:1', '/anything');
+ expect(result.error).toBe('Server timed out: fetch failed.');
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ },
+ );
+
const timedOutWriting =
'Server timed out: The operation was aborted due to timeout. The server may still have applied the request, so check before retrying.';
const timedOutReading = 'Server timed out: The operation was aborted due to timeout.';
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index 0da82c9ac..3c09db279 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -378,7 +378,16 @@ export function apiTarget(url: string, local: LocalApiDispatch | undefined): Api
}
export function isTimeoutError(err: unknown): boolean {
- return err instanceof Error && err.name === 'TimeoutError';
+ return (
+ err instanceof Error &&
+ (err.name === 'TimeoutError' ||
+ [err, err.cause].some(
+ (cause) =>
+ cause instanceof Error &&
+ 'code' in cause &&
+ (cause.code === 'UND_ERR_HEADERS_TIMEOUT' || cause.code === 'UND_ERR_BODY_TIMEOUT'),
+ ))
+ );
}
export function serverRequestFailure(err: unknown, opts?: { mutating?: boolean }): string {
@@ -435,9 +444,19 @@ async function localApiCall(
return includeHttpStatus ? { ...normalized, httpStatus: raw.status } : normalized;
}
+export function httpGet(
+ base: string,
+ path: string,
+ signal: AbortSignal,
+): Promise<{ ok: boolean; [key: string]: unknown }>;
+export function httpGet(
+ base: ApiTarget,
+ path: string,
+): Promise<{ ok: boolean; [key: string]: unknown }>;
export async function httpGet(
base: ApiTarget,
path: string,
+ signal?: AbortSignal,
): Promise<{ ok: boolean; [key: string]: unknown }> {
if (typeof base !== 'string') {
const local = await localApiCall(base.local, 'GET', path, undefined, true);
@@ -446,7 +465,7 @@ export async function httpGet(
}
let res: Response;
try {
- res = await fetch(`${base}${path}`, { signal: AbortSignal.timeout(30_000) });
+ res = await fetch(`${base}${path}`, { signal: signal ?? AbortSignal.timeout(30_000) });
} catch (err) {
return { ok: false, error: serverRequestFailure(err, { mutating: false }) };
}
diff --git a/packages/server/src/mcp/tools/shared.type-tests.ts b/packages/server/src/mcp/tools/shared.type-tests.ts
new file mode 100644
index 000000000..8b315b135
--- /dev/null
+++ b/packages/server/src/mcp/tools/shared.type-tests.ts
@@ -0,0 +1,9 @@
+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';
+import { httpGet } from './shared.ts';
+
+export function checkHttpGetCancellationTargets(local: LocalApiDispatch, signal: AbortSignal) {
+ void httpGet('http://localhost', '/api/audit', signal);
+ void httpGet({ url: 'http://localhost', local }, '/api/audit');
+ // @ts-expect-error Local dispatch does not support caller cancellation.
+ void httpGet({ url: 'http://localhost', local }, '/api/audit', signal);
+}