Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): collapse MCP tool HTTP self-calls in-process (PRD-7819) (#3319)
omar-inkeepcef98f0d2987
diff --git a/knip.config.ts b/knip.config.tsindex 13a6b9fb3..bbc8ca7cb 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -123,7 +123,9 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.tsindex b2a1b6fc3..6535662ce 100644--- a/packages/app/tests/integration/test-harness.ts+++ b/packages/app/tests/integration/test-harness.ts@@ -330,6 +330,7 @@ export async function createTestServer(options: CreateTestServerOptions = {}): PprojectDir: contentDir,config: ConfigSchema.parse({}),getServerUrl: () => `http://127.0.0.1:${port}`,+ localApi: srv.localApi,});// Wire up HTTP server + WebSocket via the canonical helper so the harnessdiff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.tsindex d7a845280..dfd95ef49 100644--- a/packages/core/src/bridge/bind-frontmatter-doc.ts+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts@@ -1,3 +1,4 @@+import type * as Y from 'yjs';import type { Err, Ok, Result } from '../config/result.ts';import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.tsindex 005627195..8bfdb40cd 100644--- a/packages/core/src/bridge/bridge-invariant.ts+++ b/packages/core/src/bridge/bridge-invariant.ts@@ -1,3 +1,4 @@+import { fnv1aDigest } from './hash-util.ts';export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex f4cc8a286..2a597ec3d 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,3 +1,4 @@+import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8fb428b90..01ef76a9f 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.tsindex 9d9c244b0..463e89595 100644--- a/packages/core/src/bridge/growth-detect.ts+++ b/packages/core/src/bridge/growth-detect.ts@@ -1,3 +1,4 @@+const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.tsindex c43fdd7e7..0939885bb 100644--- a/packages/core/src/bridge/intraline-predicate.ts+++ b/packages/core/src/bridge/intraline-predicate.ts@@ -1,3 +1,4 @@+export function rawLineCounts(doc: string): Map<string, number> {const counts = new Map<string, number>();for (const line of doc.split('\n')) {diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.tsindex 251560a35..c0dc65705 100644--- a/packages/core/src/bridge/merge-three-way.ts+++ b/packages/core/src/bridge/merge-three-way.ts@@ -65,6 +65,7 @@ export function tryLineLevelCombine(return { clean: true, merged };}+export type BridgeMergeContentLossSide = 'user' | 'agent';export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.tsindex 01ac80099..dcc5b0690 100644--- a/packages/core/src/bridge/normalize.ts+++ b/packages/core/src/bridge/normalize.ts@@ -1,3 +1,4 @@+import { stripFrontmatter } from '../extensions/frontmatter.ts';import { bodyEdgeEmpties } from './doc-boundary-space.ts';diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.tsindex 754dc5cc2..0be5203e4 100644--- a/packages/core/src/bridge/pm-structural-equivalence.ts+++ b/packages/core/src/bridge/pm-structural-equivalence.ts@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };const BR_LITERAL_RE = /^<br\s*\/?>$/i;+interface DegradeEntry {readonly label: string;readonly severity: ToleranceClassSeverity;@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {ignoreAttrs?: (attrKey: string) => boolean;}+/** Rebuild a node with `fn` applied to each child; identity when childless.* Shared by the degrade canonicalizers so none re-implements the walk. */function mapChildren(@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {return { normalized: current, fired };}+export function comparePmStructural(expected: PmStructuralNode,actual: PmStructuralNode,diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.tsindex af20de1e2..dca644141 100644--- a/packages/core/src/bridge/subsequence.ts+++ b/packages/core/src/bridge/subsequence.ts@@ -1,3 +1,4 @@+/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):* insertions in `haystack` are free; any dropped or substituted `needle` byte* fails. */diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.tsindex 83d47404a..a363dfd54 100644--- a/packages/core/src/markdown/callout-transformer.ts+++ b/packages/core/src/markdown/callout-transformer.ts@@ -1,3 +1,4 @@+import type { Blockquote, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.tsindex 9807a7e82..4499dbc92 100644--- a/packages/core/src/markdown/code-fence.ts+++ b/packages/core/src/markdown/code-fence.ts@@ -1,3 +1,4 @@+export function selectFenceChar(info: string): '`' | '~' {return info.includes('`') ? '~' : '`';}diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex 7415c474a..34704165b 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.tsindex ece5c02a1..b6299a948 100644--- a/packages/core/src/markdown/dedent-block-jsx-close.ts+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts@@ -1,3 +1,4 @@+import { findFencedRegions, isInsideFence } from './fence-regions.ts';const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.tsindex 54774764a..acd398aa6 100644--- a/packages/core/src/markdown/details-accordion-promoter.ts+++ b/packages/core/src/markdown/details-accordion-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.tsindex 43ecdc709..ba9b56384 100644--- a/packages/core/src/markdown/div-align-promoter.ts+++ b/packages/core/src/markdown/div-align-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';import type { MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.tsindex 6d3f3643e..4513da9bb 100644--- a/packages/core/src/markdown/fence-regions.ts+++ b/packages/core/src/markdown/fence-regions.ts@@ -1,3 +1,4 @@+const FENCE_RE = /^(`{3,}|~{3,})/gm;export function findFencedRegions(src: string): Array<[number, number]> {diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.tsindex 00f5771ee..6931623c7 100644--- a/packages/core/src/markdown/fixtures/index.ts+++ b/packages/core/src/markdown/fixtures/index.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {return resolve(FIXTURES_DIR, ...segments);}+interface GfmExample {section: string;markdown: string;@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];}+interface MdxCrashEntry {id: string;input: string;@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {) as LargeEmbedFixture[];}+export function loadPrd6955Before(): string {return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');}@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');}+export interface NgPinnedCase {id: string;name: string;@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {) as NgPinnedCase[];}+export function loadLargeRealistic(): string {return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');}diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.tsindex 8b1eb8519..daa3ef82b 100644--- a/packages/core/src/markdown/fixtures/perf/generate.ts+++ b/packages/core/src/markdown/fixtures/perf/generate.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;const SEED = 0xf1de1117;+function mulberry32(seed: number): () => number {let a = seed >>> 0;return () => {@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {return items[items.length - 1][0];}+const WORDS = ['lorem','ipsum',@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;}+type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';const MIX: readonly [BlockKind, number][] = [@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {return `${blocks.join('\n\n')}\n`;}+function main(): void {for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {const doc = generateDocument(count, SEED);diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.tsindex 420dc0fe5..32c055c5b 100644--- a/packages/core/src/markdown/guard-flanking-matrix.ts+++ b/packages/core/src/markdown/guard-flanking-matrix.ts@@ -7,6 +7,7 @@ import {import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';+export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;export type FlankClass = 'whitespace' | 'punctuation' | 'other';diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.tsindex 2653473da..283913255 100644--- a/packages/core/src/markdown/handler-shadow-audit.ts+++ b/packages/core/src/markdown/handler-shadow-audit.ts@@ -1,3 +1,4 @@+export interface HandlerShadowWitness {input: string;expect: 'byte' | 'byte-and-reparse-type';diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.tsindex da0a81d23..5d1000cc4 100644--- a/packages/core/src/markdown/highlight-promoter.ts+++ b/packages/core/src/markdown/highlight-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.tsindex 787315157..9681c0056 100644--- a/packages/core/src/markdown/html-to-mdast.ts+++ b/packages/core/src/markdown/html-to-mdast.ts@@ -1,3 +1,4 @@+import type { Element as HastElement, Root as HastRoot } from 'hast';import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';import rehypeParse from 'rehype-parse';@@ -128,7 +129,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRothrow new HtmlPayloadTooLargeError(html.length, maxBytes);}- const processor = unified().use(rehypeParse, { fragment: true });+ const processor = unified()+ .use(rehypeParse, { fragment: true });for (const plugin of cleanupPlugins) {processor.use(plugin);diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.tsindex 706fa9afb..994eb6917 100644--- a/packages/core/src/markdown/image-promoter.ts+++ b/packages/core/src/markdown/image-promoter.ts@@ -1,3 +1,4 @@+import type { Image, Paragraph, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.tsindex 9075aa7f1..69221627d 100644--- a/packages/core/src/markdown/index.ts+++ b/packages/core/src/markdown/index.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromPmMark,@@ -206,6 +207,7 @@ export class MarkdownManager {}}+const registry = createRegistry();function destructureAttrs(@@ -254,6 +256,7 @@ function destructureAttrs(return result;}+function hasDirtyDescendant(node: PmNode): boolean {let found = false;node.descendants((child) => {@@ -276,6 +279,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChecreturn freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;}+function isEmptyMdastParagraph(node: MdastNodes): boolean {if (node.type !== 'paragraph') return false;const children = node.children ?? [];@@ -344,6 +348,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {return out;}+import {AUDIO_EXTENSIONS,FILE_ATTACHMENT_EXTENSIONS,@@ -596,6 +601,7 @@ function buildMdastToPmHandlers(}));}+if (m.emphasis) {handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({sourceDelimiter: node.data?.sourceDelimiter ?? '*',@@ -676,6 +682,7 @@ function buildMdastToPmHandlers(}));}+if (m.link) {const sourceLiteralMark = m.sourceLiteral;handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {@@ -973,6 +980,7 @@ function buildMdastToPmHandlers(};}+const blockUnknownHandler = (node: {type: string;position?: { start: { offset: number }; end: { offset: number } };@@ -1098,6 +1106,7 @@ function buildMdastToPmHandlers(return handlers as RemarkProseMirrorOptions['handlers'];}+function buildPmToMdastHandlers(schema: Schema,freshness: FreshnessCheckerHolder,diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.tsindex fa0be9e86..b79e9aef7 100644--- a/packages/core/src/markdown/lint/applies-to.ts+++ b/packages/core/src/markdown/lint/applies-to.ts@@ -1,3 +1,4 @@+import picomatch from 'picomatch';import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.tsindex 312c9c74b..94b34dee1 100644--- a/packages/core/src/markdown/lint/config-files.ts+++ b/packages/core/src/markdown/lint/config-files.ts@@ -1,3 +1,4 @@+const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set(['.markdownlint.json','.markdownlint.jsonc',diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.tsindex 0ba33b7d8..e413367ef 100644--- a/packages/core/src/markdown/lint/config-schemas.ts+++ b/packages/core/src/markdown/lint/config-schemas.ts@@ -38,6 +38,7 @@ const fullPluginShape = Object.fromEntries(LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),) as z.ZodRawShape;+export const LinterConfigSchema = z.object({enabled: z.boolean(),plugins: z.object(fullPluginShape),diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.tsindex d48eea5e4..a51f2ffb0 100644--- a/packages/core/src/markdown/lint/default-config.ts+++ b/packages/core/src/markdown/lint/default-config.ts@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSettingMD013: false,};+export function resolveMarkdownlintConfig(rules: Record<string, MarkdownlintRuleSetting> | undefined,): Configuration {diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex ef478e268..9c9542661 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,3 +1,4 @@+import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex 0d4c9a0df..b96d19182 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,3 +1,4 @@+import Ajv, { type ValidateFunction } from 'ajv';import Ajv2019 from 'ajv/dist/2019.js';import Ajv2020 from 'ajv/dist/2020.js';diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex 00d08265a..48d260ed6 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -1,3 +1,4 @@+import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';import type { LintDiagnostic } from './types.ts';diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.tsindex 5e832aa19..be5871ed9 100644--- a/packages/core/src/markdown/lint/plugins.ts+++ b/packages/core/src/markdown/lint/plugins.ts@@ -1,3 +1,4 @@+import { z } from 'zod';import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';import {@@ -13,6 +14,7 @@ import {type MarkdownlintSlice,} from './types.ts';+const MarkdownlintRuleSettingSchema = z.union([z.boolean(),z.enum(MARKDOWNLINT_RULE_SEVERITIES),diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.tsindex 3918e657c..833c3a727 100644--- a/packages/core/src/markdown/lint/types.ts+++ b/packages/core/src/markdown/lint/types.ts@@ -1,3 +1,4 @@+export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];@@ -71,6 +72,7 @@ export interface FrontmatterSlice {schemas: ResolvedFrontmatterSchemaEntry[];}+interface RuleOptionSpecBase {key: string;description: string;diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.tsindex 98238656e..437cc539a 100644--- a/packages/core/src/markdown/lint/validation-counts.ts+++ b/packages/core/src/markdown/lint/validation-counts.ts@@ -1,3 +1,4 @@+export interface ValidationSourceCounts {errorCount: number;warningCount: number;diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.tsindex a5b511f25..bd79424c7 100644--- a/packages/core/src/markdown/math-promoter.ts+++ b/packages/core/src/markdown/math-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { Math as MdastMath } from 'mdast-util-math';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.tsindex ed89371d0..00fbc0035 100644--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Properties } from 'hast';import type { FootnoteDefinition, FootnoteReference } from 'mdast';import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.tsindex 8ce2b2492..df788a80d 100644--- a/packages/core/src/markdown/mdast-to-html.ts+++ b/packages/core/src/markdown/mdast-to-html.ts@@ -1,3 +1,4 @@+import type { Element, Root as HastRoot, Text as HastText } from 'hast';import type { Root as MdastRoot, Text as MdastText } from 'mdast';import type { Handler } from 'mdast-util-to-hast';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.tsindex 1a897fca8..17ed2b829 100644--- a/packages/core/src/markdown/mermaid-promoter.ts+++ b/packages/core/src/markdown/mermaid-promoter.ts@@ -1,3 +1,4 @@+import type { Code, Root } from 'mdast';import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.tsindex d988f4b8b..4aa0490c4 100644--- a/packages/core/src/markdown/parse-with-fallback.ts+++ b/packages/core/src/markdown/parse-with-fallback.ts@@ -168,6 +168,7 @@ export function parseRecursive(}}+interface VFilePlace {offset?: number;start?: { offset?: number };@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {return undefined;}+interface Region {start: number;end: number;@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {return null;}+export interface TagEvent {kind: 'open' | 'close' | 'self-close';name: string;@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {return { start: blockStart, end: blockEnd };}+interface SourceBlock {src: string;start: number;@@ -452,6 +456,7 @@ function tryPerBlockFallback(};}+function wholeDocRawText(source: string): JSONContent {return {type: 'doc',diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.tsindex e6ab4fd57..43d420187 100644--- a/packages/core/src/markdown/parser-drop-closure.ts+++ b/packages/core/src/markdown/parser-drop-closure.ts@@ -1,3 +1,4 @@+export type DroppedTokenAdjudication =| {kind: 'format-dof-axis';diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.tsindex 449e6f12f..5af2f05f5 100644--- a/packages/core/src/markdown/pipeline.ts+++ b/packages/core/src/markdown/pipeline.ts@@ -1,3 +1,4 @@+import {type FromProseMirrorOptions,fromProseMirror,diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.tsindex 91cdf658f..ccf06e94d 100644--- a/packages/core/src/markdown/position-aware-join.ts+++ b/packages/core/src/markdown/position-aware-join.ts@@ -1,3 +1,4 @@+import type { Join } from 'mdast-util-to-markdown';import type { Position } from 'unist';import { isBlankLineParagraph } from './zero-emission-blocks.ts';diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.tsindex 0f399d34c..e5b4c9eba 100644--- a/packages/core/src/markdown/position-slice.ts+++ b/packages/core/src/markdown/position-slice.ts@@ -1,3 +1,4 @@+import type { Nodes, Root } from 'mdast';import { visit } from 'unist-util-visit';import type { VFile } from 'vfile';@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(const first = source[startOff];if (first !== '[' && first !== '<' && !node.title) {node.data.sourceStyle = 'gfm-autolink';- } else if (first === '[') {+ }+ else if (first === '[') {const slice = source.slice(startOff, endOff);const closeBracketIdx = slice.lastIndexOf('](');if (closeBracketIdx !== -1) {diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.tsindex db10fa54b..ca225ce9b 100644--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts@@ -1,3 +1,4 @@+import type { Comment, Element, Root, Text } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.tsindex 34068d103..3a2524a9a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.tsindex 93151d43b..2279a0189 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.tsindex 188f02d83..a0f467c42 100644--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.tsindex 4ba2c3418..4e8542a21 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.tsindex 1a74b1272..a3c96b24a 100644--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.tsindex de35e7b79..e95cf43d6 100644--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts@@ -1,3 +1,4 @@+import type { Comment, Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.tsindex b4be1b2ea..ffdb4d5b5 100644--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts@@ -1,3 +1,4 @@+import type { Element, ElementContent, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.tsindex 3c8d88b7c..e2a96d1a7 100644--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts@@ -1,3 +1,4 @@+import type { Element, Root } from 'hast';import type { Plugin } from 'unified';diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.tsindex cf2c9da8e..0389575ac 100644--- a/packages/core/src/markdown/resolve-image-url.ts+++ b/packages/core/src/markdown/resolve-image-url.ts@@ -1,3 +1,4 @@+import { isRelativeUrl } from './safe-url.ts';function isDevDiagnosticContext(): boolean {diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.tsindex 0dd54070e..96304e7a5 100644--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts@@ -1,3 +1,4 @@+import type { JSONContent } from '@tiptap/core';import type { Nodes } from 'mdast';import { expect } from 'vitest';diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.tsindex 7cac5b042..93798cf83 100644--- a/packages/core/src/markdown/serialize-helpers.ts+++ b/packages/core/src/markdown/serialize-helpers.ts@@ -1,3 +1,4 @@+import type { Node as PmNode } from '@tiptap/pm/model';import type {MdxJsxAttribute,diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.tsindex b012a5aff..8c08b7a04 100644--- a/packages/core/src/markdown/single-dollar-math-promoter.ts+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts@@ -1,3 +1,4 @@+import type { PhrasingContent, Root, Text } from 'mdast';import type { InlineMath } from 'mdast-util-math';import { SKIP, visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.tsindex 3e79f8cb6..959cc0bd2 100644--- a/packages/core/src/markdown/to-markdown-handlers.ts+++ b/packages/core/src/markdown/to-markdown-handlers.ts@@ -1,3 +1,4 @@+import type { Nodes, Parents } from 'mdast';import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';import type { Handle, Info, State } from 'mdast-util-to-markdown';diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.tsindex 0f1b0f27d..6e6d73400 100644--- a/packages/core/src/markdown/underline-promoter.ts+++ b/packages/core/src/markdown/underline-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import type { MdxJsxTextElement } from 'mdast-util-mdx';import { visit } from 'unist-util-visit';diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.tsindex 1a082bda7..932d7d2a8 100644--- a/packages/core/src/markdown/unknown-mdast-guard.ts+++ b/packages/core/src/markdown/unknown-mdast-guard.ts@@ -1,3 +1,4 @@+import type { Root as MdastRoot } from 'mdast';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.tsindex d578476a7..ac9f5239b 100644--- a/packages/core/src/markdown/whitespace-char-ref.ts+++ b/packages/core/src/markdown/whitespace-char-ref.ts@@ -1,3 +1,4 @@+const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([[0x20, ' '],[0x09, '\t'],diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.tsindex 6dad26200..afd9936fe 100644--- a/packages/core/src/markdown/wiki-link-micromark.ts+++ b/packages/core/src/markdown/wiki-link-micromark.ts@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {}}+const CODE_BANG = 33; // !const CODE_LBRACKET = 91; // [const CODE_RBRACKET = 93; // ]@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {};}+function enterWikiLink(this: CompileContext, token: Token) {this.enter({@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {unsafe: [{ character: '[', inConstruct: ['phrasing'] }],};+const MICROMARK_EXT = wikiLinkSyntax();export function remarkWikiLink(this: Processor) {diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex ae5d1e171..31e98778e 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -599,6 +599,7 @@ import {import { errnoCode, parseQuery } from './http/handler-utils.ts';import { assertSingleRouterOwnership, type NativeApiHandle } from './http/http-app.ts';import { createLinkGraphRoutes } from './http/link-graph-routes.ts';+import { createLocalApiDispatch, type LocalApiDispatch } from './http/local-api-dispatch.ts';import { methodRouter } from './http/method-router.ts';import { createMetricsRoutes } from './http/metrics-routes.ts';import { getRequestId } from './http/request-id.ts';@@ -2784,7 +2785,7 @@ export interface CommentDocHooks {export function createApiExtension(options: ApiExtensionOptions,-): Extension & { nativeApi: NativeApiHandle } {+): Extension & { nativeApi: NativeApiHandle; localApi: LocalApiDispatch } {const { durabilityState, remotePublicHost } = options;// Every local-op call site in this factory inherits the remote-origin// widening through this shadow — one choke point, zero per-site churn.@@ -22328,11 +22329,59 @@ export function createApiExtension(},};+ // In-process dispatch for MCP tools mounted on this same server process.+ // Allowlist: endpoints whose handlers are thin marshaling over a+ // capability service (`services/*`) or the derived-document-index reads —+ // for these the HTTP self-call collapses to a function call with the same+ // handler producing the same wire body. Everything else (CRDT paired+ // writes, rename, rollback/restore, sync/conflicts, history, lint/audit,+ // template + skill CRUD) has no extracted service yet and stays on HTTP;+ // extend this set as further capabilities extract.+ const MCP_LOCAL_API_PATHS: ReadonlySet<string> = new Set([+ // searchService+ '/api/search',+ // fileOpsService+ '/api/delete-path',+ '/api/create-folder',+ // versionOpsService+ '/api/save-version',+ // skillImportService+ '/api/skill/import',+ // skillPlacementOps / skillInstallOps+ '/api/skill/install',+ // assetService (multipart body rides the synthetic request into busboy)+ '/api/upload',+ // derived-document-index reads (native link-graph group)+ '/api/orphans',+ '/api/hubs',+ '/api/backlinks',+ '/api/forward-links',+ '/api/dead-links',+ '/api/suggest-links',+ ]);+ // Every collapsed path must resolve to a handler at construction — a typo+ // here, or a later route rename, would otherwise fall back to HTTP forever+ // with no signal. Same posture as `assertSingleRouterOwnership` above.+ for (const path of MCP_LOCAL_API_PATHS) {+ if (routes[path] === undefined && linkGraphRoutes.table.resolve(path)?.dispatch === undefined) {+ throw new Error(`MCP_LOCAL_API_PATHS has no handler for ${path}`);+ }+ }+ const localApi = createLocalApiDispatch({+ resolve: (pathname) => {+ if (!MCP_LOCAL_API_PATHS.has(pathname)) return undefined;+ const legacy = routes[pathname];+ if (legacy !== undefined) return legacy;+ return linkGraphRoutes.table.resolve(pathname)?.dispatch;+ },+ });+return {priority: 100, // Higher priority — API routes run before static file servingasync onRequest({ request, response }: { request: IncomingMessage; response: ServerResponse }) {await runApiPipeline(request, response);},nativeApi,+ localApi,};}diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex 204f5f555..c4a30036f 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -755,6 +755,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {projectDir: opts.projectDir ?? opts.contentDir,config: opts.config,getServerUrl: () => `http://${mcpHost}:${boundPort}`,+ localApi: serverInstance.localApi,log,});diff --git a/packages/server/src/http/local-api-dispatch.test.ts b/packages/server/src/http/local-api-dispatch.test.tsnew file mode 100644index 000000000..5387bbb9d--- /dev/null+++ b/packages/server/src/http/local-api-dispatch.test.ts@@ -0,0 +1,312 @@+/**+ * Unit + transport-parity coverage for the in-process MCP dispatch.+ *+ * The parity suite is the load-bearing half: every behavior class a+ * collapsed handler can exhibit (schema-validated success, in-handler+ * problem+json error, thrown error, query-string read, multipart upload)+ * runs through BOTH transports — a real `node:http` listener and+ * `createLocalApiDispatch` — and the (status, body) pair must match+ * byte-for-byte, modulo the per-response `instance` correlation UUID.+ */++import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';+import type { AddressInfo } from 'node:net';+import { BridgeMergeContentLossError } from '@inkeep/open-knowledge-core';+import busboy from 'busboy';+import { afterAll, describe, expect, it } from 'vitest';+import { z } from 'zod';+import { catchErrors } from './catch-errors.ts';+import { errorResponse } from './error-response.ts';+import { createLocalApiDispatch, type LocalApiDispatch } from './local-api-dispatch.ts';+import { withValidation } from './request-validation.ts';+import { successResponse } from './success-response.ts';++const EchoSuccessSchema = z.looseObject({ echoed: z.unknown() });+const QuerySuccessSchema = z.looseObject({ q: z.string().nullable() });+const UploadSuccessSchema = z.looseObject({ field: z.string(), fileBytes: z.number() });++type Handler = (req: IncomingMessage, res: ServerResponse) => Promise<void> | void;++const handlers: Record<string, Handler> = {+ '/api/echo': withValidation(+ z.looseObject({ value: z.string() }),+ catchErrors(+ async (_req, res, body) => {+ successResponse(res, 200, EchoSuccessSchema, { echoed: body.value }, { handler: 'echo' });+ },+ { handler: 'echo', title: 'Failed to echo.' },+ ),+ { handler: 'echo', method: 'POST' },+ ),+ '/api/query': withValidation(+ z.looseObject({}),+ catchErrors(+ async (req, res) => {+ const url = new URL(req.url ?? '', 'http://localhost');+ successResponse(+ res,+ 200,+ QuerySuccessSchema,+ { q: url.searchParams.get('q') },+ { handler: 'query' },+ );+ },+ { handler: 'query', title: 'Failed to query.' },+ ),+ { handler: 'query', method: 'GET', skipBodyParse: true },+ ),+ '/api/reject': withValidation(+ z.looseObject({}),+ catchErrors(+ async (_req, res) => {+ errorResponse(res, 404, 'urn:ok:error:doc-not-found', 'No such thing.', {+ handler: 'reject',+ detail: 'It is simply not there.',+ });+ },+ { handler: 'reject', title: 'Failed to reject.' },+ ),+ { handler: 'reject', method: 'POST' },+ ),+ '/api/throw': withValidation(+ z.looseObject({}),+ catchErrors(+ async () => {+ throw new Error('boom');+ },+ { handler: 'throw', title: 'Failed to compute.' },+ ),+ { handler: 'throw', method: 'POST' },+ ),+ // Throws OUTSIDE any catchErrors boundary — exercises the dispatch's own+ // last-resort envelope (HTTP side: the listener wrapper below mirrors the+ // admission pipeline's catch).+ '/api/throw-raw': async () => {+ throw new Error('raw-boom');+ },+ '/api/upload-lite': (req, res) =>+ new Promise<void>((resolve) => {+ const bb = busboy({ headers: req.headers });+ let field = '';+ let fileBytes = 0;+ bb.on('field', (name, value) => {+ if (name === 'field') field = value;+ });+ bb.on('file', (_name, stream) => {+ stream.on('data', (chunk: Buffer) => {+ fileBytes += chunk.length;+ });+ stream.on('close', () => {});+ });+ bb.on('close', () => {+ successResponse(+ res,+ 200,+ UploadSuccessSchema,+ { field, fileBytes },+ { handler: 'upload-lite' },+ );+ resolve();+ });+ req.pipe(bb);+ }),+};++const resolveHandler = (pathname: string): Handler | undefined => handlers[pathname];++const local: LocalApiDispatch = createLocalApiDispatch({ resolve: resolveHandler });++// Real listener over the same handlers, with the admission pipeline's+// last-resort catch semantics (500 envelope on an escaped throw).+const server = createServer((req, res) => {+ const pathname = (req.url ?? '/').split('?')[0] ?? '/';+ const handler = resolveHandler(pathname);+ if (!handler) {+ res.statusCode = 404;+ res.end('not found');+ return;+ }+ void (async () => {+ try {+ await handler(req, res);+ } catch (err) {+ if (!res.headersSent && !res.writableEnded && !res.destroyed) {+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {+ handler: pathname,+ cause: err,+ });+ }+ }+ })();+});+const port = await new Promise<number>((resolve) => {+ server.listen(0, '127.0.0.1', () => {+ resolve((server.address() as AddressInfo).port);+ });+});++afterAll(() => {+ server.closeAllConnections();+ server.close();+});++/** Strip the per-response `instance` UUID so bodies compare stably. */+function comparable(bodyText: string): unknown {+ try {+ const parsed = JSON.parse(bodyText) as Record<string, unknown>;+ const { instance: _instance, ...rest } = parsed;+ return rest;+ } catch {+ return bodyText;+ }+}++async function overHttp(+ method: string,+ path: string,+ body?: string | Uint8Array,+ contentType?: string,+): Promise<{ status: number; bodyText: string }> {+ const res = await fetch(`http://127.0.0.1:${port}${path}`, {+ method,+ headers: contentType !== undefined ? { 'content-type': contentType } : undefined,+ body,+ });+ return { status: res.status, bodyText: await res.text() };+}++describe('createLocalApiDispatch', () => {+ it('returns null for paths outside the resolver allowlist', async () => {+ expect(await local('GET', '/api/not-collapsed')).toBeNull();+ });++ it('strips the query string before resolving but hands it to the handler', async () => {+ const result = await local('GET', '/api/query?q=hello%20there');+ expect(result).not.toBeNull();+ expect(result?.status).toBe(200);+ expect(JSON.parse(result?.bodyText ?? '')).toEqual({ q: 'hello there' });+ });++ it('BridgeMergeContentLossError becomes the same 500 envelope, not a rejection', async () => {+ // The dispatch is the transport's terminal response boundary — like the+ // admission pipeline it envelopes the escape (cause-logged), and unlike+ // the pipeline it has no request-logging layer above to re-throw into.+ // Pin that the caller sees the standard envelope, never the raw error.+ const lossErr = new BridgeMergeContentLossError({+ which: 'merged',+ side: 'local',+ lostSubstrings: ['lost content'],+ } as ConstructorParameters<typeof BridgeMergeContentLossError>[0]);+ const lossy = createLocalApiDispatch({+ resolve: () => async () => {+ throw lossErr;+ },+ });+ const result = await lossy('POST', '/api/anything', {+ body: '{}',+ contentType: 'application/json',+ });+ expect(result?.status).toBe(500);+ expect(JSON.parse(result?.bodyText ?? '')).toMatchObject({+ type: 'urn:ok:error:internal-server-error',+ title: 'Internal server error.',+ });+ });++ it('rejects with the fetch-parity TimeoutError when the handler never responds', async () => {+ const hanging = createLocalApiDispatch({+ resolve: () => async () => {+ await new Promise(() => {});+ },+ timeoutMs: 50,+ });+ await expect(hanging('GET', '/api/anything')).rejects.toMatchObject({+ name: 'TimeoutError',+ message: 'The operation was aborted due to timeout',+ });+ });++ describe('transport parity (local vs real HTTP listener, same handlers)', () => {+ it('schema-validated success body', async () => {+ const body = JSON.stringify({ value: 'parity' });+ const viaHttp = await overHttp('POST', '/api/echo', body, 'application/json');+ const viaLocal = await local('POST', '/api/echo', { body, contentType: 'application/json' });+ expect(viaHttp.status).toBe(200);+ expect(viaLocal?.status).toBe(viaHttp.status);+ expect(comparable(viaLocal?.bodyText ?? '')).toEqual(comparable(viaHttp.bodyText));+ });++ it('request-validation 400 (schema mismatch, field-path detail)', async () => {+ const body = JSON.stringify({ value: 42 });+ const viaHttp = await overHttp('POST', '/api/echo', body, 'application/json');+ const viaLocal = await local('POST', '/api/echo', { body, contentType: 'application/json' });+ expect(viaHttp.status).toBe(400);+ expect(viaLocal?.status).toBe(400);+ expect(comparable(viaLocal?.bodyText ?? '')).toEqual(comparable(viaHttp.bodyText));+ });++ it('method mismatch 405', async () => {+ const viaHttp = await overHttp('GET', '/api/echo');+ const viaLocal = await local('GET', '/api/echo');+ expect(viaHttp.status).toBe(405);+ expect(viaLocal?.status).toBe(405);+ expect(comparable(viaLocal?.bodyText ?? '')).toEqual(comparable(viaHttp.bodyText));+ });++ it('in-handler problem+json error with detail', async () => {+ const viaHttp = await overHttp('POST', '/api/reject', '{}', 'application/json');+ const viaLocal = await local('POST', '/api/reject', {+ body: '{}',+ contentType: 'application/json',+ });+ expect(viaHttp.status).toBe(404);+ expect(viaLocal?.status).toBe(404);+ expect(comparable(viaLocal?.bodyText ?? '')).toEqual(comparable(viaHttp.bodyText));+ });++ it('throw inside catchErrors → per-handler 500 title', async () => {+ const viaHttp = await overHttp('POST', '/api/throw', '{}', 'application/json');+ const viaLocal = await local('POST', '/api/throw', {+ body: '{}',+ contentType: 'application/json',+ });+ expect(viaHttp.status).toBe(500);+ expect(viaLocal?.status).toBe(500);+ expect(comparable(viaLocal?.bodyText ?? '')).toEqual(comparable(viaHttp.bodyText));+ expect(JSON.parse(viaLocal?.bodyText ?? '')).toMatchObject({ title: 'Failed to compute.' });+ });++ it('throw that escapes the handler → last-resort 500 envelope', async () => {+ const viaHttp = await overHttp('POST', '/api/throw-raw', '{}', 'application/json');+ const viaLocal = await local('POST', '/api/throw-raw', {+ body: '{}',+ contentType: 'application/json',+ });+ expect(viaHttp.status).toBe(500);+ expect(viaLocal?.status).toBe(500);+ expect(comparable(viaLocal?.bodyText ?? '')).toEqual(comparable(viaHttp.bodyText));+ expect(JSON.parse(viaLocal?.bodyText ?? '')).toMatchObject({+ title: 'Internal server error.',+ });+ });++ it('multipart body reaches busboy identically', async () => {+ const form = new FormData();+ form.append('field', 'hello');+ form.append('file', new Blob([new Uint8Array(1024).fill(7)]), 'blob.bin');+ const encoded = new Request('http://localhost/api/upload-lite', {+ method: 'POST',+ body: form,+ });+ const contentType = encoded.headers.get('content-type') ?? '';+ const bytes = new Uint8Array(await encoded.arrayBuffer());++ const viaHttp = await overHttp('POST', '/api/upload-lite', bytes, contentType);+ const viaLocal = await local('POST', '/api/upload-lite', { body: bytes, contentType });+ expect(viaHttp.status).toBe(200);+ expect(viaLocal?.status).toBe(200);+ expect(comparable(viaLocal?.bodyText ?? '')).toEqual(comparable(viaHttp.bodyText));+ expect(JSON.parse(viaLocal?.bodyText ?? '')).toEqual({ field: 'hello', fileBytes: 1024 });+ });+ });+});diff --git a/packages/server/src/http/local-api-dispatch.ts b/packages/server/src/http/local-api-dispatch.tsnew file mode 100644index 000000000..6d6db3a7c--- /dev/null+++ b/packages/server/src/http/local-api-dispatch.ts@@ -0,0 +1,262 @@+/**+ * In-process dispatch for MCP tool self-calls.+ *+ * The MCP tools mounted on the project server (`mcp-http.ts`) historically+ * reached server capabilities by issuing HTTP requests to their own listener+ * — a full TCP + HTTP-parse round trip to a handler living in the same+ * process. With the capability services extracted (`services/*`), the+ * handlers behind those endpoints are thin marshaling layers, so the+ * self-call can collapse to a function call: run the SAME handler against a+ * synthetic req/res pair and hand the captured wire body back to the tool.+ *+ * Byte parity is structural — the handler code that writes the HTTP+ * response writes the local response, and the tool-side normalization+ * (`normalizeResponse` in `mcp/tools/shared.ts`) consumes both transports+ * through one code path. Attribution parity is structural for the same+ * reason: identity rides the request body exactly as it does over HTTP+ * (precedent #24 — identity at entry).+ *+ * The dispatch deliberately does NOT run the `/api/*` admission pipeline+ * (`api-pipeline.ts`): request-id echo, CORS, and the loopback/workspace-Host+ * mutating gates defend the network listener. A same-process caller is+ * inside that trust boundary already — a self-call over HTTP always+ * originated from loopback and passed those gates vacuously.+ *+ * Skipping the pipeline also skips its telemetry triple: the HTTP SERVER+ * span, the `http.server.request.duration{http.route}` histogram sample,+ * and the `api.access` log line. Collapsed MCP traffic therefore leaves+ * the `/api/*`-keyed observability surfaces and shows up instead on the+ * MCP tool layer (`mcp/tool-telemetry.ts`: `mcp.tool.<name>` span ++ * `ok.mcp.tool.duration` histogram + per-tool error counting), which+ * already answers per-call latency and error rate for agent traffic.+ * Anything keyed on `http.route` for these endpoints sees browser/SDK+ * traffic only once this ships.+ *+ * Scope is allowlist-gated by the resolver the api extension supplies:+ * only endpoints whose handlers are thin over a capability service+ * (or an equally thin primitive like the derived-document-index reads)+ * resolve; everything else returns `null` and the tool falls back to HTTP.+ */++import { EventEmitter } from 'node:events';+import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http';+import { Readable } from 'node:stream';+import { errorResponse } from './error-response.ts';++type LocalApiMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';++interface LocalApiRequestOptions {+ /** Pre-serialized request body (JSON string, or raw bytes for multipart). */+ body?: string | Uint8Array;+ /** `Content-Type` header value; required for multipart (carries boundary). */+ contentType?: string;+}++/** Captured wire result — what the HTTP transport would have delivered. */+interface LocalApiResult {+ status: number;+ bodyText: string;+}++/**+ * Dispatch a request in-process. Resolves `null` when the path is outside+ * the collapsed allowlist — the caller then falls back to real HTTP.+ */+export type LocalApiDispatch = (+ method: LocalApiMethod,+ pathWithQuery: string,+ options?: LocalApiRequestOptions,+) => Promise<LocalApiResult | null>;++type NodeHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void> | void;++export interface CreateLocalApiDispatchOptions {+ /** Allowlist-gated handler lookup (query string already stripped). */+ resolve: (pathname: string) => NodeHandler | undefined;+ /**+ * Upper bound on handler completion. Matches the MCP shim's HTTP fetch+ * timeout (`mcp/tools/shared.ts`) so both transports share the same+ * cancellation deadline and surface the same timeout error text. Like the+ * HTTP timeout, expiry rejects the caller but does NOT abort the running+ * handler — its side effects may still complete after the deadline.+ */+ timeoutMs?: number;+}++/**+ * Minimal `ServerResponse` stand-in: enough surface for the sanctioned wire+ * emitters (`successResponse` / `errorResponse` / handler-local writes) to+ * run to completion, capturing status + body instead of writing a socket.+ */+class SyntheticResponse extends EventEmitter {+ statusCode = 200;+ headersSent = false;+ writableEnded = false;+ destroyed = false;+ readonly req: IncomingMessage;+ private readonly headers = new Map<string, string | number | readonly string[]>();+ private readonly chunks: Buffer[] = [];+ private settle: (() => void) | undefined;+ /**+ * Resolves when the handler ends the response. Named to avoid the real+ * `ServerResponse.finished` (a deprecated boolean) — a handler probing+ * that legacy flag must not find a truthy Promise here.+ */+ readonly settled: Promise<void>;++ constructor(req: IncomingMessage) {+ super();+ this.req = req;+ this.settled = new Promise<void>((resolve) => {+ this.settle = resolve;+ });+ }++ setHeader(name: string, value: string | number | readonly string[]): this {+ this.headers.set(name.toLowerCase(), value);+ return this;+ }++ getHeader(name: string): string | number | readonly string[] | undefined {+ return this.headers.get(name.toLowerCase());+ }++ removeHeader(name: string): void {+ this.headers.delete(name.toLowerCase());+ }++ writeHead(status: number, headers?: OutgoingHttpHeaders): this {+ this.statusCode = status;+ if (headers) {+ for (const [name, value] of Object.entries(headers)) {+ if (value !== undefined) this.headers.set(name.toLowerCase(), value as string);+ }+ }+ this.headersSent = true;+ return this;+ }++ write(chunk: unknown): boolean {+ this.headersSent = true;+ this.appendChunk(chunk);+ return true;+ }++ end(chunk?: unknown): this {+ if (this.writableEnded) return this;+ if (chunk !== undefined) this.appendChunk(chunk);+ this.headersSent = true;+ this.writableEnded = true;+ this.settle?.();+ this.emit('finish');+ this.emit('close');+ return this;+ }++ private appendChunk(chunk: unknown): void {+ if (typeof chunk === 'string') {+ this.chunks.push(Buffer.from(chunk, 'utf8'));+ } else if (chunk instanceof Buffer) {+ this.chunks.push(chunk);+ } else if (chunk instanceof Uint8Array) {+ this.chunks.push(Buffer.from(chunk));+ }+ }++ bodyText(): string {+ return Buffer.concat(this.chunks).toString('utf8');+ }+}++function syntheticRequest(+ method: LocalApiMethod,+ pathWithQuery: string,+ options: LocalApiRequestOptions,+): IncomingMessage {+ const bodyBytes =+ options.body === undefined+ ? []+ : [+ typeof options.body === 'string'+ ? Buffer.from(options.body, 'utf8')+ : Buffer.from(options.body),+ ];+ const req = Readable.from(bodyBytes) as unknown as IncomingMessage;+ req.method = method;+ req.url = pathWithQuery;+ // The full body is buffered before dispatch, so the request is complete by+ // construction. Handlers that guard the client-disconnect race (`'close'`+ // with `!req.complete`, e.g. the upload spine) must not read the stream's+ // natural end-of-data close as an abort.+ req.complete = true;+ req.headers = {+ host: 'localhost',+ ...(options.contentType !== undefined ? { 'content-type': options.contentType } : {}),+ };+ return req;+}++export function createLocalApiDispatch(opts: CreateLocalApiDispatchOptions): LocalApiDispatch {+ const timeoutMs = opts.timeoutMs ?? 30_000;+ return async (method, pathWithQuery, options = {}) => {+ const queryStart = pathWithQuery.indexOf('?');+ const pathname = queryStart === -1 ? pathWithQuery : pathWithQuery.slice(0, queryStart);+ const handler = opts.resolve(pathname);+ if (handler === undefined) return null;++ const req = syntheticRequest(method, pathWithQuery, options);+ const res = new SyntheticResponse(req);++ const run = (async () => {+ try {+ await handler(req, res as unknown as ServerResponse);+ } catch (err) {+ // Mirror the admission pipeline's last-resort envelope: a throw that+ // escaped the handler's own error boundary becomes a typed RFC 9457+ // 500 (guarded against double-write), so the tool sees the same wire+ // body either transport delivers. `errorResponse` logs with `cause`,+ // covering the logging the pipeline's re-throw path provides.+ //+ // `BridgeMergeContentLossError` gets the SAME treatment, on purpose,+ // and that is not a violation of the one-RECOVERY-catch STOP rule+ // (Observer A Path B in `server-observers.ts`): this catch detects+ // and recovers nothing — like the pipeline's terminal catch it turns+ // the escape into the standard 500 envelope, and the `cause`-logged+ // `errorResponse` carries the same observability signal the pipeline+ // emits for it over HTTP. The pipeline additionally re-throws, but+ // only because Hocuspocus request logging sits above it; no such+ // layer exists here, and a re-throw would reach the tool's generic+ // text catch instead — an UNlogged flatten that also breaks response+ // parity with HTTP for exactly this class.+ if (!res.headersSent && !res.writableEnded && !res.destroyed) {+ errorResponse(+ res as unknown as ServerResponse,+ 500,+ 'urn:ok:error:internal-server-error',+ 'Internal server error.',+ { handler: pathname, cause: err },+ );+ }+ }+ await res.settled;+ })();++ // Same deadline + error text the HTTP transport produces when+ // `AbortSignal.timeout` fires inside `fetch`, so the tool-side+ // `Server unreachable: <message>` diagnostic is byte-identical.+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ reject(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));+ }, timeoutMs);+ timer.unref?.();+ });+ try {+ await Promise.race([run, timeout]);+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }++ return { status: res.statusCode, bodyText: res.bodyText() };+ };+}diff --git a/packages/server/src/mcp-http.ts b/packages/server/src/mcp-http.tsindex 7cd083c0a..646d05f3e 100644--- a/packages/server/src/mcp-http.ts+++ b/packages/server/src/mcp-http.ts@@ -6,6 +6,7 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/import { validateAgentId } from './agent-id.ts';import type { Config } from './config/schema.ts';import { MCP_SERVER_NAME } from './constants.ts';+import type { LocalApiDispatch } from './http/local-api-dispatch.ts';import {type AgentIdentity,MCP_CONNECTION_ID_HEADER,@@ -35,6 +36,15 @@ export interface McpHttpHandlerOptions {config: Config;/** Returns the base URL of this running HTTP server, without the `/mcp` suffix. */getServerUrl: () => string;+ /**+ * In-process `/api/*` dispatch (`ServerInstance.localApi`). When present,+ * tools whose endpoints are backed by the extracted capability services+ * invoke the handler in-process instead of round-tripping HTTP to their+ * own listener; paths outside the collapsed allowlist fall back to HTTP.+ * The stdio `ok mcp` proxy never has this — it talks to a separate server+ * process and stays on HTTP.+ */+ localApi?: LocalApiDispatch;log?: {info?: (obj: object, msg: string) => void;warn?: (obj: object, msg: string) => void;@@ -119,6 +129,7 @@ function createSessionServer(const configuredRoot = opts.projectDir ?? opts.contentDir;registerAllTools(server, {serverUrl: async () => opts.getServerUrl(),+ localApi: opts.localApi,resolveCwd: async (explicit?: string) => {if (explicit === undefined) return configuredRoot;const result = resolveWithinRoot(configuredRoot, explicit);diff --git a/packages/server/src/mcp-local-dispatch-parity.test.ts b/packages/server/src/mcp-local-dispatch-parity.test.tsnew file mode 100644index 000000000..3dd20a13a--- /dev/null+++ b/packages/server/src/mcp-local-dispatch-parity.test.ts@@ -0,0 +1,281 @@+import { describe as _bunDescribe, afterAll, beforeAll, expect, test } from 'vitest';++// Same skip-on-CI gate as boot.test.ts (oven-sh/bun#11892): boots a real+// server; local runs + the full check gate cover it.+const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;++import { mkdirSync, writeFileSync } from 'node:fs';+import { mkdtemp, rm } from 'node:fs/promises';+import { createServer, type Server } from 'node:http';+import type { AddressInfo } from 'node:net';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { OK_DIR } from '@inkeep/open-knowledge-core';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { type BootedServer, bootServer } from './boot.ts';+import { ConfigSchema } from './config/schema.ts';+import { createMcpHttpHandler, type McpHttpHandler } from './mcp-http.ts';++/**+ * End-to-end transport parity for the collapsed MCP self-calls: the SAME+ * project server answers two MCP sessions — the boot-mounted `/mcp` (wired+ * with `localApi`, so collapsed tools dispatch in-process) and a side+ * handler created WITHOUT `localApi` (every tool call round-trips HTTP).+ * For each covered tool the two sessions' final MCP responses must match+ * after masking genuinely per-call fields (timings).+ */++const TEST_CONFIG = ConfigSchema.parse({});++let tmpDir: string;+let booted: BootedServer;+let httpOnlyMcp: McpHttpHandler;+let sideServer: Server;+let localClient: Client;+let httpClient: Client;++type ToolResult = {+ content?: Array<{ type: string; text?: string }>;+ structuredContent?: unknown;+ isError?: boolean;+};++function seedOkScaffold(projectDir: string): void {+ const okDir = resolve(projectDir, OK_DIR);+ mkdirSync(okDir, { recursive: true });+ writeFileSync(resolve(okDir, 'config.yml'), '', 'utf-8');+ writeFileSync(resolve(okDir, '.gitignore'), '', 'utf-8');+}++async function connectClient(url: string, name: string): Promise<Client> {+ const client = new Client({ name, version: '0.0.0-test' });+ await client.connect(new StreamableHTTPClientTransport(new URL(url)));+ return client;+}++/** Mask per-call volatile fields so the two transports compare stably. */+function maskVolatile(result: ToolResult): unknown {+ return JSON.parse(+ JSON.stringify({+ isError: result.isError ?? false,+ text: result.content?.map((c) => c.text ?? '').join('\n') ?? '',+ structured: result.structuredContent ?? null,+ }),+ (key, value) => (key === 'elapsedMs' ? null : value),+ );+}++async function callBoth(name: string, args: Record<string, unknown>): Promise<[unknown, unknown]> {+ const viaLocal = (await localClient.callTool({ name, arguments: args })) as ToolResult;+ const viaHttp = (await httpClient.callTool({ name, arguments: args })) as ToolResult;+ return [maskVolatile(viaLocal), maskVolatile(viaHttp)];+}++beforeAll(async () => {+ tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-mcp-parity-'));+ const contentDir = resolve(tmpDir, 'project');+ mkdirSync(contentDir, { recursive: true });+ seedOkScaffold(contentDir);+ writeFileSync(resolve(contentDir, 'alpha.md'), '# Alpha\n\nThe alpha reference doc.\n', 'utf-8');+ writeFileSync(+ resolve(contentDir, 'beta.md'),+ '# Beta\n\nSee [[alpha]] and the missing [[gamma-nowhere]].\n',+ 'utf-8',+ );+ writeFileSync(resolve(contentDir, 'del-local.md'), '# Doomed\n\nSame body.\n', 'utf-8');+ writeFileSync(resolve(contentDir, 'del-http.md'), '# Doomed\n\nSame body.\n', 'utf-8');++ booted = await bootServer({+ host: '127.0.0.1',+ config: TEST_CONFIG,+ contentDir,+ port: 0,+ quiet: true,+ gitEnabled: false,+ idleShutdownMs: null,+ attachUiSibling: false,+ });+ await booted.ready;++ // Side MCP endpoint against the SAME server, minus localApi — the pure-HTTP+ // control arm of the comparison.+ httpOnlyMcp = createMcpHttpHandler({+ contentDir: booted.contentDir,+ projectDir: booted.contentDir,+ config: TEST_CONFIG,+ getServerUrl: () => `http://127.0.0.1:${booted.port}`,+ });+ sideServer = createServer((req, res) => {+ void httpOnlyMcp.handle(req, res);+ });+ const sidePort = await new Promise<number>((resolvePort) => {+ sideServer.listen(0, '127.0.0.1', () => {+ resolvePort((sideServer.address() as AddressInfo).port);+ });+ });++ localClient = await connectClient(`http://127.0.0.1:${booted.port}/mcp`, 'parity-suite');+ httpClient = await connectClient(`http://127.0.0.1:${sidePort}/mcp`, 'parity-suite');++ // Wait out the search-index warmup so the read comparisons are stable.+ const deadline = Date.now() + 15_000;+ for (;;) {+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/search`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ query: 'alpha' }),+ });+ const body = (await res.json()) as { ready?: boolean };+ if (body.ready !== false) break;+ if (Date.now() > deadline) throw new Error('search index never became ready');+ await new Promise((r) => setTimeout(r, 250));+ }+}, 60_000);++afterAll(async () => {+ await localClient?.close().catch(() => {});+ await httpClient?.close().catch(() => {});+ await httpOnlyMcp?.close();+ sideServer?.closeAllConnections();+ sideServer?.close();+ await booted?.destroy();+ await rm(tmpDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+});++describe('MCP local-dispatch transport parity (same server, two sessions)', () => {+ test('collapsed calls never touch the HTTP listener; the control arm does', async () => {+ const apiHits: string[] = [];+ const onRequest = (req: { url?: string }): void => {+ if (req.url?.startsWith('/api/')) apiHits.push(req.url.split('?')[0] ?? '');+ };+ booted.httpServer.on('request', onRequest);+ try {+ await localClient.callTool({ name: 'search', arguments: { query: 'alpha' } });+ expect(apiHits).toEqual([]);+ await httpClient.callTool({ name: 'search', arguments: { query: 'alpha' } });+ expect(apiHits).toEqual(['/api/search']);+ } finally {+ booted.httpServer.off('request', onRequest);+ }+ });++ test('links — backlinks / forward / orphans / hubs / dead in one multi-kind call', async () => {+ const [viaLocal, viaHttp] = await callBoth('links', {+ kind: ['backlinks', 'forward', 'orphans', 'hubs', 'dead'],+ document: 'alpha',+ });+ expect(viaLocal).toEqual(viaHttp);+ });++ test('links — suggest', async () => {+ const [viaLocal, viaHttp] = await callBoth('links', { kind: 'suggest', document: 'alpha' });+ expect(viaLocal).toEqual(viaHttp);+ });++ test('search — success path returns identical hits', async () => {+ const [viaLocal, viaHttp] = await callBoth('search', { query: 'alpha' });+ expect(viaLocal).toEqual(viaHttp);+ });++ test('search — server-side 400 (over-long query) surfaces identically', async () => {+ const [viaLocal, viaHttp] = await callBoth('search', { query: 'x'.repeat(250) });+ expect(viaLocal).toEqual(viaHttp);+ expect((viaLocal as { text: string }).text).toContain('Query is too long (max 200 chars).');+ });++ test('checkpoint — snapshot lands through both transports', async () => {+ const [viaLocal, viaHttp] = await callBoth('checkpoint', {});+ // Each call mints its own checkpoint commit; the SHA is the one+ // legitimately different byte-run between the transports.+ const normalize = (value: unknown): unknown =>+ JSON.parse(JSON.stringify(value).replace(/[0-9a-f]{40}/g, '<sha>'));+ expect(normalize(viaLocal)).toEqual(normalize(viaHttp));+ expect((viaLocal as { text: string }).text).toContain('Checkpoint saved.');+ });++ test('delete — document delete lands with identical response shape', async () => {+ const viaLocal = (await localClient.callTool({+ name: 'delete',+ arguments: { document: 'del-local' },+ })) as ToolResult;+ const viaHttp = (await httpClient.callTool({+ name: 'delete',+ arguments: { document: 'del-http' },+ })) as ToolResult;+ // Different docs (each session deletes its own), so normalize the names+ // before comparing the full response.+ const normalize = (result: ToolResult, doc: string): unknown =>+ JSON.parse(JSON.stringify(maskVolatile(result)).replaceAll(doc, '<doc>'));+ expect(normalize(viaLocal, 'del-local')).toEqual(normalize(viaHttp, 'del-http'));+ expect(viaLocal.isError ?? false).toBe(false);+ });++ test('delete — missing document error surfaces identically', async () => {+ const [viaLocal, viaHttp] = await callBoth('delete', { document: 'never-existed' });+ expect(viaLocal).toEqual(viaHttp);+ expect((viaLocal as { isError: boolean }).isError).toBe(true);+ });++ test('write — asset upload via multipart lands through both transports', async () => {+ const bytesA = Buffer.from('local-transport-bytes-1234567890');+ const bytesB = Buffer.from('http--transport-bytes-1234567890');+ const viaLocal = (await localClient.callTool({+ name: 'write',+ arguments: {+ asset: { path: 'assets/local-side.bin', content: bytesA.toString('base64') },+ },+ })) as ToolResult;+ const viaHttp = (await httpClient.callTool({+ name: 'write',+ arguments: {+ asset: { path: 'assets/http-side.bin', content: bytesB.toString('base64') },+ },+ })) as ToolResult;+ expect(viaLocal.isError ?? false).toBe(false);+ expect(viaHttp.isError ?? false).toBe(false);+ const normalize = (result: ToolResult, name: string): unknown =>+ JSON.parse(JSON.stringify(maskVolatile(result)).replaceAll(name, '<name>'));+ expect(normalize(viaLocal, 'local-side')).toEqual(normalize(viaHttp, 'http-side'));+ });++ test('write — folder create lands through both transports', async () => {+ const viaLocal = (await localClient.callTool({+ name: 'write',+ arguments: { folder: { path: 'made/by-local' } },+ })) as ToolResult;+ const viaHttp = (await httpClient.callTool({+ name: 'write',+ arguments: { folder: { path: 'made/by-httpx' } },+ })) as ToolResult;+ expect(viaLocal.isError ?? false).toBe(false);+ const normalize = (result: ToolResult, leaf: string): unknown =>+ JSON.parse(JSON.stringify(maskVolatile(result)).replaceAll(leaf, '<leaf>'));+ expect(normalize(viaLocal, 'by-local')).toEqual(normalize(viaHttp, 'by-httpx'));+ });++ test('write — folder create conflict (409) surfaces identically', async () => {+ const [viaLocal, viaHttp] = await callBoth('write', { folder: { path: 'made/by-local' } });+ expect(viaLocal).toEqual(viaHttp);+ expect((viaLocal as { isError: boolean }).isError).toBe(true);+ });++ // Deliberately no success-path arms for `/api/skill/import` and+ // `/api/skill/install`: their responses are not deterministic even between+ // two consecutive plain-HTTP calls — the reported bundle `path` and the+ // "now lives at" location ordering depend on editor-host detection against+ // the developer's real home dir and on background projection fan-out+ // timing relative to response assembly. A byte-compare here measures that+ // race, not the transport. Their marshaling (validation, envelopes, error+ // mapping) is pinned by the CI-run handler-level parity suite+ // (`http/local-api-dispatch.test.ts`); the deterministic error path is+ // compared below.+ test('install — unknown skill error surfaces identically', async () => {+ const [viaLocal, viaHttp] = await callBoth('install', {+ name: 'no-such-skill-here',+ add: ['claude'],+ });+ expect(viaLocal).toEqual(viaHttp);+ expect((viaLocal as { isError: boolean }).isError).toBe(true);+ });+});diff --git a/packages/server/src/mcp/tools/checkpoint.ts b/packages/server/src/mcp/tools/checkpoint.tsindex dfef1ed0c..805187503 100644--- a/packages/server/src/mcp/tools/checkpoint.ts+++ b/packages/server/src/mcp/tools/checkpoint.ts@@ -8,9 +8,11 @@* `restore_version` is the per-doc restore counterpart.*/import { z } from 'zod';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import type { AgentIdentity } from '../agent-identity.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {+ apiTarget,HOCUSPOCUS_NOT_RUNNING_ERROR,httpPost,outputSchemaWithText,@@ -37,6 +39,7 @@ export interface CheckpointDeps {config: ConfigOrResolver;resolveCwd: (explicit?: string) => Promise<string>;identityRef?: { current: AgentIdentity };+ localApi?: LocalApiDispatch;}export function register(server: ServerInstance, deps: CheckpointDeps): void {@@ -69,7 +72,7 @@ export function register(server: ServerInstance, deps: CheckpointDeps): void {if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);const identity = deps.identityRef?.current;- const result = await httpPost(url, '/api/save-version', {+ const result = await httpPost(apiTarget(url, deps.localApi), '/api/save-version', {...(args.summary !== undefined ? { summary: args.summary } : {}),...(identity? {diff --git a/packages/server/src/mcp/tools/delete.ts b/packages/server/src/mcp/tools/delete.tsindex f16c989df..fbfd08d56 100644--- a/packages/server/src/mcp/tools/delete.ts+++ b/packages/server/src/mcp/tools/delete.ts@@ -9,11 +9,13 @@* - template → `DELETE /api/template` (server, attributed) [Requires: Hocuspocus]*/import { z } from 'zod';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import type { AgentIdentity } from '../agent-identity.ts';import { resolvePreviewUrlForTool } from './preview-url.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {agentIdentityFields,+ apiTarget,HOCUSPOCUS_NOT_RUNNING_ERROR,httpDelete,httpPost,@@ -54,6 +56,7 @@ interface DeleteDeps {config: ConfigOrResolver;resolveCwd: (explicit?: string) => Promise<string>;identityRef?: { current: AgentIdentity };+ localApi?: LocalApiDispatch;}interface DeleteOneResult {@@ -82,7 +85,7 @@ async function deleteOneDoc(// `Error: ${r.error}`.if (!normalized.ok)return { docName: rawDocName, ok: false, error: normalized.error.replace(/^Error:\s*/, '') };- const result = await httpPost(url, '/api/delete-path', {+ const result = await httpPost(apiTarget(url, deps.localApi), '/api/delete-path', {kind: 'file',path: normalized.docName,...agentIdentityFields(deps.identityRef?.current),@@ -311,7 +314,7 @@ export function register(server: ServerInstance, deps: DeleteDeps): void {// Folder.if (args.folder !== undefined) {- const result = await httpPost(url, '/api/delete-path', {+ const result = await httpPost(apiTarget(url, deps.localApi), '/api/delete-path', {kind: 'folder',path: folderPath,...agentIdentityFields(deps.identityRef?.current),@@ -327,7 +330,7 @@ export function register(server: ServerInstance, deps: DeleteDeps): void {// Asset.if (args.asset !== undefined) {const path = args.asset.path.replace(/^\/+/, '').replace(/\/+$/, '');- const result = await httpPost(url, '/api/delete-path', {+ const result = await httpPost(apiTarget(url, deps.localApi), '/api/delete-path', {kind: 'asset',path,...agentIdentityFields(deps.identityRef?.current),diff --git a/packages/server/src/mcp/tools/import.ts b/packages/server/src/mcp/tools/import.tsindex 20192fef8..392b435fd 100644--- a/packages/server/src/mcp/tools/import.ts+++ b/packages/server/src/mcp/tools/import.ts@@ -17,10 +17,12 @@ import {} from '@inkeep/open-knowledge-core';import { parseSkillsShSource } from '@inkeep/open-knowledge-core/skills-catalog';import { z } from 'zod';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import type { AgentIdentity } from '../agent-identity.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {agentIdentityFields,+ apiTarget,httpPost,outputSchemaWithText,ROUTED_CWD_DESCRIPTION,@@ -49,6 +51,7 @@ interface ImportDeps {config: ConfigOrResolver;resolveCwd: (explicit?: string) => Promise<string>;identityRef?: { current: AgentIdentity };+ localApi?: LocalApiDispatch;}export function register(server: ServerInstance, deps: ImportDeps): void {@@ -130,7 +133,7 @@ export function register(server: ServerInstance, deps: ImportDeps): void {);if (!context.ok) return context.result;- const result = await httpPost(context.url, '/api/skill/import', {+ const result = await httpPost(apiTarget(context.url, deps.localApi), '/api/skill/import', {source: args.source,...(args.skill !== undefined ? { skill: args.skill } : {}),// Acquire only. The placement below runs through the install path so@@ -157,7 +160,7 @@ export function register(server: ServerInstance, deps: ImportDeps): void {// math here. A failure leaves the skill acquired at its source folder —// reported, not silently swallowed, so the caller knows to retry the// placement rather than the fetch.- const placed = await httpPost(context.url, '/api/skill/install', {+ const placed = await httpPost(apiTarget(context.url, deps.localApi), '/api/skill/install', {...(args.scope !== undefined ? { scope: args.scope } : {}),name,add: args.add,diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.tsindex 291d54220..dd3665eb7 100644--- a/packages/server/src/mcp/tools/index.ts+++ b/packages/server/src/mcp/tools/index.ts@@ -31,6 +31,7 @@*/import { createEnsureSingleFileSession } from '../../ensure-single-file-session.ts';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import type { AgentIdentity } from '../agent-identity.ts';import { getCurrentMcpLogger, type McpLogger } from '../logger.ts';import { createLoggedServer } from '../tool-logging.ts';@@ -76,6 +77,15 @@ interface RegisterAllToolsOptions {serverUrl?: ServerUrlOrResolver;/** Resolves the cwd for a given tool call (see `ResolveCwd` docs). */resolveCwd: ResolveCwd;+ /**+ * In-process `/api/*` dispatch (`ServerInstance.localApi`), present only+ * when the MCP server runs inside the project server process+ * (`mcp-http.ts`). Tools whose endpoints are backed by the extracted+ * capability services then invoke the handler in-process instead of+ * HTTP-round-tripping to their own listener; the stdio proxy omits this+ * and stays on HTTP.+ */+ localApi?: LocalApiDispatch;config: ConfigOrResolver;identityRef?: { current: AgentIdentity };logger?: McpLogger;@@ -130,6 +140,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOresolveCwd: named('search'),config: opts.config,serverUrl: opts.serverUrl,+ localApi: opts.localApi,});// Unified link-graph reader — replaces the six dedicated getters// (get_backlinks, get_forward_links, get_dead_links, get_orphans, get_hubs,@@ -138,6 +149,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOserverUrl: opts.serverUrl,config: opts.config,resolveCwd: named('links'),+ localApi: opts.localApi,});// Markdown lint — surface rule violations (single doc or project-wide audit);// `fix: true` applies auto-fixes through the agent-write spine, so it takes@@ -167,6 +179,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOconfig: opts.config,resolveCwd: named('write'),identityRef: opts.identityRef,+ localApi: opts.localApi,});registerEdit(registrationServer, {serverUrl: opts.serverUrl,@@ -179,6 +192,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOconfig: opts.config,resolveCwd: named('delete'),identityRef: opts.identityRef,+ localApi: opts.localApi,});// `move` — move/rename a document, folder, or asset; probes the content// directory to set `kind` and rewrites the link graph.@@ -195,6 +209,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOconfig: opts.config,resolveCwd: named('install'),identityRef: opts.identityRef,+ localApi: opts.localApi,});// `import` — acquire a skill from skills.sh / github / git URL / local path into// `.ok/skills` as versioned content (the marketplace on-ramp). Pairs with@@ -204,6 +219,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOconfig: opts.config,resolveCwd: named('import'),identityRef: opts.identityRef,+ localApi: opts.localApi,});registerHistory(registrationServer, {serverUrl: opts.serverUrl,@@ -224,6 +240,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsOconfig: opts.config,resolveCwd: named('checkpoint'),identityRef: opts.identityRef,+ localApi: opts.localApi,});registerRestoreVersion(registrationServer, {serverUrl: opts.serverUrl,diff --git a/packages/server/src/mcp/tools/install.ts b/packages/server/src/mcp/tools/install.tsindex 49a9b6229..145842481 100644--- a/packages/server/src/mcp/tools/install.ts+++ b/packages/server/src/mcp/tools/install.ts@@ -19,10 +19,12 @@ import {type SkillScope,} from '@inkeep/open-knowledge-core';import { z } from 'zod';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import type { AgentIdentity } from '../agent-identity.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {agentIdentityFields,+ apiTarget,errorTextWithDetail,httpPost,httpPut,@@ -95,6 +97,7 @@ interface InstallDeps {config: ConfigOrResolver;resolveCwd: (explicit?: string) => Promise<string>;identityRef?: { current: AgentIdentity };+ localApi?: LocalApiDispatch;}export function register(server: ServerInstance, deps: InstallDeps): void {@@ -229,13 +232,17 @@ export function register(server: ServerInstance, deps: InstallDeps): void {// it records no skill-wide default — a later `add` still follows the form// the skill already uses.for (const target of args.convert ?? []) {- const converted = await httpPost(context.url, '/api/skill/install', {- ...(args.scope !== undefined ? { scope: args.scope } : {}),- name: args.name,- convert: { target, mode: args.mode },- ...(args.summary !== undefined ? { summary: args.summary } : {}),- ...agentIdentityFields(deps.identityRef?.current),- });+ const converted = await httpPost(+ apiTarget(context.url, deps.localApi),+ '/api/skill/install',+ {+ ...(args.scope !== undefined ? { scope: args.scope } : {}),+ name: args.name,+ convert: { target, mode: args.mode },+ ...(args.summary !== undefined ? { summary: args.summary } : {}),+ ...agentIdentityFields(deps.identityRef?.current),+ },+ );if (!converted.ok) return textResult(errorTextWithDetail(converted), true);}// A pure convert changes no membership, so there is no location math to@@ -261,7 +268,7 @@ export function register(server: ServerInstance, deps: InstallDeps): void {// would also convert the claude and codex symlinks the caller never named.// This tool's `mode` is scoped to `add`, so it is applied below as a// per-location convert — the same verb the app uses for one row.- const result = await httpPost(context.url, '/api/skill/install', {+ const result = await httpPost(apiTarget(context.url, deps.localApi), '/api/skill/install', {...(args.scope !== undefined ? { scope: args.scope } : {}),name: args.name,...(args.add !== undefined ? { add: args.add } : {}),@@ -275,7 +282,7 @@ export function register(server: ServerInstance, deps: InstallDeps): void {// Shape ONLY the locations just added. An already-correct form converges// server-side, so re-stating it is a no-op rather than a rewrite.for (const target of args.mode !== undefined ? (args.add ?? []) : []) {- const shaped = await httpPost(context.url, '/api/skill/install', {+ const shaped = await httpPost(apiTarget(context.url, deps.localApi), '/api/skill/install', {...(args.scope !== undefined ? { scope: args.scope } : {}),name: args.name,convert: { target, mode: args.mode },diff --git a/packages/server/src/mcp/tools/links.ts b/packages/server/src/mcp/tools/links.tsindex ecce284b6..fb89065b0 100644--- a/packages/server/src/mcp/tools/links.ts+++ b/packages/server/src/mcp/tools/links.ts@@ -9,9 +9,12 @@import { ORPHAN_MODES, type OrphanMode } from '@inkeep/open-knowledge-core';import { z } from 'zod';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import { buildListResolver, type PreviewUrlDeps, resolvePreviewUrlForTool } from './preview-url.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {+ type ApiTarget,+ apiTarget,HOCUSPOCUS_NOT_RUNNING_ERROR,httpGet,looseObjectArray,@@ -65,6 +68,7 @@ interface HubsPayload {export interface LinksDeps extends PreviewUrlDeps {serverUrl: ServerUrlOrResolver;config: ConfigOrResolver;+ localApi?: LocalApiDispatch;}interface LinksArgs {@@ -164,7 +168,7 @@ export function register(server: ServerInstance, deps: LinksDeps): void {const { resolve } = await buildListResolver(deps, cwd);const outcomes = await Promise.all(- kinds.map((kind) => runKind(kind, args, url, cwd, deps, resolve)),+ kinds.map((kind) => runKind(kind, args, apiTarget(url, deps.localApi), cwd, deps, resolve)),);const merged: Record<string, unknown> = {};@@ -198,37 +202,37 @@ export function register(server: ServerInstance, deps: LinksDeps): void {function runKind(kind: LinkKind,args: LinksArgs,- url: string,+ target: ApiTarget,cwd: string,deps: LinksDeps,resolve: ListResolve,): Promise<KindOutcome> {switch (kind) {case 'backlinks':- return runBacklinks(args, url, resolve);+ return runBacklinks(args, target, resolve);case 'forward':- return runForwardLinks(args, url, resolve);+ return runForwardLinks(args, target, resolve);case 'dead':- return runDeadLinks(args, url, resolve);+ return runDeadLinks(args, target, resolve);case 'orphans':- return runOrphans(args, url, resolve);+ return runOrphans(args, target, resolve);case 'hubs':- return runHubs(args, url, resolve);+ return runHubs(args, target, resolve);case 'suggest':- return runSuggest(args, url, cwd, deps);+ return runSuggest(args, target, cwd, deps);}}async function runBacklinks(args: LinksArgs,- url: string,+ target: ApiTarget,resolve: ListResolve,): Promise<KindOutcome> {if (!args.document) return { ok: false, error: 'kind=backlinks requires `document`.' };const normalized = normalizeDocName(args.document);if (!normalized.ok) return { ok: false, error: normalized.error };const result = await httpGet(- url,+ target,`/api/backlinks?docName=${encodeURIComponent(normalized.docName)}`,);if (!result.ok) return { ok: false, error: String(result.error) };@@ -248,14 +252,14 @@ async function runBacklinks(async function runForwardLinks(args: LinksArgs,- url: string,+ target: ApiTarget,resolve: ListResolve,): Promise<KindOutcome> {if (!args.document) return { ok: false, error: 'kind=forward requires `document`.' };const normalized = normalizeDocName(args.document);if (!normalized.ok) return { ok: false, error: normalized.error };const result = await httpGet(- url,+ target,`/api/forward-links?docName=${encodeURIComponent(normalized.docName)}`,);if (!result.ok) return { ok: false, error: String(result.error) };@@ -277,7 +281,7 @@ async function runForwardLinks(async function runDeadLinks(args: LinksArgs,- url: string,+ target: ApiTarget,resolve: ListResolve,): Promise<KindOutcome> {const params = new URLSearchParams();@@ -287,7 +291,7 @@ async function runDeadLinks(params.append('sourceDocName', normalized.docName);}const query = params.toString();- const result = await httpGet(url, `/api/dead-links${query ? `?${query}` : ''}`);+ const result = await httpGet(target, `/api/dead-links${query ? `?${query}` : ''}`);if (!result.ok) return { ok: false, error: String(result.error) };const { ok: _ok, ...rest } = result;const data = rest as DeadLinksPayload;@@ -318,11 +322,11 @@ async function runDeadLinks(async function runOrphans(args: LinksArgs,- url: string,+ target: ApiTarget,resolve: ListResolve,): Promise<KindOutcome> {const query = args.mode ? `?mode=${encodeURIComponent(args.mode)}` : '';- const result = await httpGet(url, `/api/orphans${query}`);+ const result = await httpGet(target, `/api/orphans${query}`);if (!result.ok) return { ok: false, error: String(result.error) };const { ok: _ok, ...rest } = result;const data = rest as OrphansPayload;@@ -338,9 +342,13 @@ async function runOrphans(return { ok: true, data: { orphans } };}-async function runHubs(args: LinksArgs, url: string, resolve: ListResolve): Promise<KindOutcome> {+async function runHubs(+ args: LinksArgs,+ target: ApiTarget,+ resolve: ListResolve,+): Promise<KindOutcome> {const query = args.limit ? `?limit=${encodeURIComponent(String(args.limit))}` : '';- const result = await httpGet(url, `/api/hubs${query}`);+ const result = await httpGet(target, `/api/hubs${query}`);if (!result.ok) return { ok: false, error: String(result.error) };const { ok: _ok, ...rest } = result;const data = rest as HubsPayload;@@ -358,7 +366,7 @@ async function runHubs(args: LinksArgs, url: string, resolve: ListResolve): Promasync function runSuggest(args: LinksArgs,- url: string,+ target: ApiTarget,cwd: string,deps: LinksDeps,): Promise<KindOutcome> {@@ -366,7 +374,7 @@ async function runSuggest(const normalized = normalizeDocName(args.document);if (!normalized.ok) return { ok: false, error: normalized.error };const result = await httpGet(- url,+ target,`/api/suggest-links?docName=${encodeURIComponent(normalized.docName)}`,);if (!result.ok) return { ok: false, error: String(result.error) };diff --git a/packages/server/src/mcp/tools/search.ts b/packages/server/src/mcp/tools/search.tsindex 734696f09..b6365a8a3 100644--- a/packages/server/src/mcp/tools/search.ts+++ b/packages/server/src/mcp/tools/search.ts@@ -12,6 +12,7 @@*/import { z } from 'zod';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import {buildListResolver,docNameFromPath,@@ -20,6 +21,7 @@ import {} from './preview-url.ts';import type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {+ apiTarget,HOCUSPOCUS_NOT_RUNNING_ERROR,httpPost,outputSchemaWithText,@@ -54,6 +56,7 @@ interface SearchDeps {resolveCwd: (explicit?: string) => Promise<string>;config: ConfigOrResolver;serverUrl: ServerUrlOrResolver;+ localApi?: LocalApiDispatch;}const SCOPE_VALUES = ['page', 'folder', 'content', 'file'] as const;@@ -306,7 +309,11 @@ export function register(server: ServerInstance, deps: SearchDeps): void {};if (args.scopes) body.scopes = args.scopes;- const result = (await httpPost(url, '/api/search', body)) as SearchApiResponse;+ const result = (await httpPost(+ apiTarget(url, deps.localApi),+ '/api/search',+ body,+ )) as SearchApiResponse;if (!result.ok) {// `result.error` is guaranteed to be a string by// `normalizeResponse` — RFC 9457 `title`, body'sdiff --git a/packages/server/src/mcp/tools/shared.test.ts b/packages/server/src/mcp/tools/shared.test.tsindex 8785c7ccd..fa7ed63dc 100644--- a/packages/server/src/mcp/tools/shared.test.ts+++ b/packages/server/src/mcp/tools/shared.test.ts@@ -16,6 +16,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest';import { z } from 'zod';import { type Config, ConfigSchema } from '../../config/schema.ts';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';import {HOCUSPOCUS_NOT_RUNNING_ERROR,@@ -569,6 +570,85 @@ describe('httpPost', () => {});});+// ── ApiTarget object form (in-process local dispatch) ──+//+// The composition layer between the tools and `createLocalApiDispatch`:+// a dispatch result must ride the same normalization tail as HTTP, a+// `null` must fall back to HTTP against `url`, a throw must surface as the+// transport-failure diagnostic, and the `httpStatus` field must keep its+// GET-only asymmetry.++describe('ApiTarget local dispatch', () => {+ const jsonDispatch =+ (status: number, body: unknown): LocalApiDispatch =>+ async () => ({ status, bodyText: JSON.stringify(body) });++ test('httpGet: dispatch result is normalized and carries httpStatus', async () => {+ const result = await httpGet(+ { url: 'http://localhost:1', local: jsonDispatch(200, { data: 'hello' }) },+ '/api/anything',+ );+ expect(result.ok).toBe(true);+ expect(result.data).toBe('hello');+ expect(result.httpStatus).toBe(200);+ });++ test('httpPost: dispatch result is normalized and omits httpStatus', async () => {+ const result = await httpPost(+ { url: 'http://localhost:1', local: jsonDispatch(200, { received: true }) },+ '/api/anything',+ { key: 'value' },+ );+ expect(result.ok).toBe(true);+ expect(result.received).toBe(true);+ expect(result.httpStatus).toBeUndefined();+ });++ test('problem+json from the dispatch normalizes like the HTTP path', async () => {+ const result = await httpPost(+ {+ url: 'http://localhost:1',+ local: jsonDispatch(404, {+ type: 'urn:ok:error:doc-not-found',+ title: 'Not found.',+ status: 404,+ }),+ },+ '/api/anything',+ );+ expect(result.ok).toBe(false);+ expect(result.error).toBe('Not found.');+ expect(result.status).toBe(404);+ });++ test('null from the dispatch falls back to HTTP against url', async () => {+ const nullDispatch: LocalApiDispatch = async () => null;+ const result = await httpGet({ url: baseUrl, local: nullDispatch }, '/flat-success');+ expect(result.ok).toBe(true);+ expect(result.data).toBe('hello');+ });++ test('dispatch throw surfaces as the transport-failure diagnostic', async () => {+ const throwDispatch: LocalApiDispatch = async () => {+ throw new Error('boom');+ };+ const result = await httpPost(+ { url: 'http://localhost:1', local: throwDispatch },+ '/api/anything',+ );+ expect(result.ok).toBe(false);+ expect(result.error).toBe('Server unreachable: boom');+ });++ test('non-JSON 2xx bodyText: contract-violation error with httpStatus on GET', async () => {+ const htmlDispatch: LocalApiDispatch = async () => ({ status: 200, bodyText: '<html>' });+ const result = await httpGet({ url: 'http://localhost:1', local: htmlDispatch }, '/api/x');+ expect(result.ok).toBe(false);+ expect(result.error).toContain('2xx response with non-JSON body');+ expect(result.httpStatus).toBe(200);+ });+});+// ── Wire-shape canonicalization (RFC 9457 + flat success) ──//// Exercises the production wire shapes the MCP shim's `normalizeResponse`diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.tsindex 6447ef913..b1ffc19fa 100644--- a/packages/server/src/mcp/tools/shared.ts+++ b/packages/server/src/mcp/tools/shared.ts@@ -19,6 +19,7 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';import type { Config } from '../../config/schema.ts';import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import type { AgentIdentity } from '../agent-identity.ts';import { resolveWithinRoot } from './path-safety.ts';@@ -558,7 +559,10 @@ export function normalizeDocName(* automatically pick up new typed extensions (e.g. `colliding[]`) without a* per-tool change.*/-function normalizeResponse(res: Response, body: unknown): { ok: boolean; [key: string]: unknown } {+function normalizeResponse(+ res: { ok: boolean; status: number },+ body: unknown,+): { ok: boolean; [key: string]: unknown } {// 2xx success path takes precedence over body-shape inspection.// `res.ok` is the wire-level success/error discriminator; the// problem+json shape and the non-object reject are only consulted on@@ -647,6 +651,75 @@ function normalizeResponse(res: Response, body: unknown): { ok: boolean; [key: sreturn { ...rest, ok: false, error: fallbackError };}+/**+ * Transport target for the Hocuspocus API helpers. A plain URL string keeps+ * the HTTP path (the stdio `ok mcp` proxy — a separate process from the+ * server). The object form additionally carries the in-process dispatch+ * (`ServerInstance.localApi`) available when the MCP session runs inside+ * the server process itself: collapsed endpoints then invoke their handler+ * as a function call, and paths outside the collapsed allowlist fall back+ * to HTTP against `url`. Both transports share the JSON-parse ++ * `normalizeResponse` tail, so the tool-facing result is identical either+ * way the same wire bytes arrive.+ */+export type ApiTarget = string | { url: string; local: LocalApiDispatch };++/** Build an {@link ApiTarget}: in-process dispatch when available, else HTTP. */+export function apiTarget(url: string, local: LocalApiDispatch | undefined): ApiTarget {+ return local ? { url, local } : url;+}++/**+ * Run a collapsed call through the in-process dispatch, applying the same+ * response normalization as the HTTP path. Returns `null` when the path is+ * outside the collapsed allowlist (caller falls back to HTTP).+ * `includeHttpStatus` mirrors `httpGet`'s extra `httpStatus` field, which+ * `httpSend` deliberately does not carry.+ */+async function localApiCall(+ local: LocalApiDispatch,+ method: 'GET' | 'POST' | 'PUT' | 'DELETE',+ path: string,+ serializedBody: string | undefined,+ includeHttpStatus: boolean,+): Promise<{ ok: boolean; [key: string]: unknown } | null> {+ let raw: { status: number; bodyText: string } | null;+ try {+ raw = await local(+ method,+ path,+ serializedBody !== undefined+ ? { body: serializedBody, contentType: 'application/json' }+ : undefined,+ );+ } catch (err) {+ return { ok: false, error: `Server unreachable: ${err instanceof Error ? err.message : err}` };+ }+ if (raw === null) return null;+ const ok = raw.status >= 200 && raw.status <= 299;+ let body: unknown;+ try {+ body = JSON.parse(raw.bodyText);+ } catch (parseErr) {+ const detail = parseErr instanceof Error ? parseErr.message : String(parseErr);+ const statusFields = includeHttpStatus ? { httpStatus: raw.status } : {};+ if (ok) {+ return {+ ok: false,+ ...statusFields,+ error: `Server returned 2xx response with non-JSON body: ${detail}`,+ };+ }+ return {+ ok: false,+ ...statusFields,+ error: `Server returned HTTP ${raw.status} with non-JSON body: ${detail}`,+ };+ }+ const normalized = normalizeResponse({ ok, status: raw.status }, body);+ return includeHttpStatus ? { ...normalized, httpStatus: raw.status } : normalized;+}+/*** HTTP GET helper for Hocuspocus API calls.* Returns `{ ok: false, error }` on network failure or non-JSON response.@@ -655,12 +728,17 @@ function normalizeResponse(res: Response, body: unknown): { ok: boolean; [key: s* `normalizeResponse` above.*/export async function httpGet(- baseUrl: string,+ base: ApiTarget,path: string,): Promise<{ ok: boolean; [key: string]: unknown }> {+ if (typeof base !== 'string') {+ const local = await localApiCall(base.local, 'GET', path, undefined, true);+ if (local !== null) return local;+ base = base.url;+ }let res: Response;try {- res = await fetch(`${baseUrl}${path}`, { signal: AbortSignal.timeout(30_000) });+ res = await fetch(`${base}${path}`, { signal: AbortSignal.timeout(30_000) });} catch (err) {return { ok: false, error: `Server unreachable: ${err instanceof Error ? err.message : err}` };}@@ -707,13 +785,13 @@ export async function httpGet(* (e.g. search's `backend` / `degraded`).*/export async function httpGetRows(- baseUrl: string,+ base: ApiTarget,path: string,field: string,): Promise<{ error: string } | { rows: Array<Record<string, unknown>>; data: Record<string, unknown> }> {- const result = await httpGet(baseUrl, path);+ const result = await httpGet(base, path);if (!result.ok) {return { error: typeof result.error === 'string' ? result.error : 'request failed' };}@@ -733,7 +811,7 @@ export async function httpGetRows(*/async function httpSend(method: 'POST' | 'PUT' | 'DELETE',- baseUrl: string,+ base: ApiTarget,path: string,body?: Record<string, unknown>,): Promise<{ ok: boolean; [key: string]: unknown }> {@@ -751,9 +829,14 @@ async function httpSend(};}}+ if (typeof base !== 'string') {+ const local = await localApiCall(base.local, method, path, serializedBody, false);+ if (local !== null) return local;+ base = base.url;+ }let res: Response;try {- res = await fetch(`${baseUrl}${path}`, {+ res = await fetch(`${base}${path}`, {method,headers: serializedBody !== undefined ? { 'Content-Type': 'application/json' } : undefined,body: serializedBody,@@ -785,26 +868,26 @@ async function httpSend(}export function httpPost(- baseUrl: string,+ base: ApiTarget,path: string,body?: Record<string, unknown>,): Promise<{ ok: boolean; [key: string]: unknown }> {- return httpSend('POST', baseUrl, path, body);+ return httpSend('POST', base, path, body);}export function httpPut(- baseUrl: string,+ base: ApiTarget,path: string,body?: Record<string, unknown>,): Promise<{ ok: boolean; [key: string]: unknown }> {- return httpSend('PUT', baseUrl, path, body);+ return httpSend('PUT', base, path, body);}export function httpDelete(- baseUrl: string,+ base: ApiTarget,path: string,): Promise<{ ok: boolean; [key: string]: unknown }> {- return httpSend('DELETE', baseUrl, path);+ return httpSend('DELETE', base, path);}/**diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.tsindex 2e0f15b46..f53588072 100644--- a/packages/server/src/mcp/tools/write.ts+++ b/packages/server/src/mcp/tools/write.ts@@ -36,6 +36,7 @@ import { mergePatch } from '../../content/frontmatter-merge.ts';import { parentFolderOf } from '../../content/nested-folder-rules.ts';import { applySubstitution, todayIsoUtc } from '../../content/substitution.ts';import { resolveTemplatesAvailable } from '../../content/templates-resolver.ts';+import type { LocalApiDispatch } from '../../http/local-api-dispatch.ts';import type { AgentIdentity } from '../agent-identity.ts';import {formatAdvisoryBriefs,@@ -49,6 +50,7 @@ import { buildPreviewAttachWarning, resolvePreviewUrl, START_UI_TEXT_HINT } fromimport type { ConfigOrResolver, ServerInstance, ServerUrlOrResolver } from './shared.ts';import {agentIdentityFields,+ apiTarget,docExtensionOnDisk,documentResultBaseShape,HOCUSPOCUS_NOT_RUNNING_ERROR,@@ -107,6 +109,7 @@ interface WriteDeps {config: ConfigOrResolver;resolveCwd: (explicit?: string) => Promise<string>;identityRef?: { current: AgentIdentity };+ localApi?: LocalApiDispatch;}interface DocSpec {@@ -425,7 +428,7 @@ async function handleFolder() {if (!url) return textResult(HOCUSPOCUS_NOT_RUNNING_ERROR, true);const identity = deps.identityRef?.current;- const result = await httpPost(url, '/api/create-folder', {+ const result = await httpPost(apiTarget(url, deps.localApi), '/api/create-folder', {path: folder.path,...(summary !== undefined ? { summary } : {}),...agentIdentityFields(identity),@@ -552,19 +555,63 @@ async function handleAsset(let resBody: { ok: boolean; status: number; data?: Record<string, unknown>; error?: string };try {- const res = await fetch(`${url}/api/upload${qs ? `?${qs}` : ''}`, {- method: 'POST',- body: form,- });- const data = (await res.json().catch(() => null)) as Record<string, unknown> | null;- resBody = res.ok- ? { ok: true, status: res.status, data: data ?? {} }+ const uploadPath = `/api/upload${qs ? `?${qs}` : ''}`;+ let status: number;+ let bodyText: string;+ // In-process dispatch when mounted on the server: the multipart body is+ // encoded once via `Request` (boundary lands in the content-type header)+ // and rides the synthetic request into the same busboy handler HTTP+ // reaches. The stdio proxy has no `localApi` and keeps the fetch. Both+ // arms reduce to (status, bodyText) so the parse and mapping below are+ // shared — the transports cannot diverge in how a response is read.+ const localApi = deps.localApi;+ const local = localApi+ ? await (async () => {+ const encoded = new Request('http://localhost/api/upload', {+ method: 'POST',+ body: form,+ });+ const contentType = encoded.headers.get('content-type') ?? 'multipart/form-data';+ const bytes = new Uint8Array(await encoded.arrayBuffer());+ return localApi('POST', uploadPath, { body: bytes, contentType });+ })()+ : null;+ if (local !== null) {+ status = local.status;+ bodyText = local.bodyText;+ } else {+ const res = await fetch(`${url}${uploadPath}`, {+ method: 'POST',+ body: form,+ signal: AbortSignal.timeout(30_000),+ });+ status = res.status;+ bodyText = await res.text();+ }+ const ok = status >= 200 && status <= 299;+ let data: Record<string, unknown> | null;+ try {+ data = JSON.parse(bodyText) as Record<string, unknown>;+ } catch (parseErr) {+ // A non-JSON body on this JSON endpoint is a contract violation even+ // on 2xx — surfacing it beats reporting success with no usable embed+ // reference. Same diagnostic shape as `httpGet`/`httpSend`.+ const detail = parseErr instanceof Error ? parseErr.message : String(parseErr);+ return textResult(+ ok+ ? `Error: Server returned 2xx response with non-JSON body: ${detail}`+ : `Error: Server returned HTTP ${status} with non-JSON body: ${detail}`,+ true,+ );+ }+ resBody = ok+ ? { ok: true, status, data: data ?? {} }: {ok: false,- status: res.status,+ status,error:(data && (typeof data.title === 'string' ? data.title : (data.error as string))) ||- `Upload failed (HTTP ${res.status}).`,+ `Upload failed (HTTP ${status}).`,};} catch (err) {return textResult(`Error: upload request failed: ${(err as Error).message}`, true);diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 143042b96..5b0204257 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -133,6 +133,7 @@ import type {import { type HeadWatcherHandle, readProjectHeadState, startHeadWatcher } from './head-watcher.ts';import { errnoCode } from './http/handler-utils.ts';import type { NativeApiHandle } from './http/http-app.ts';+import type { LocalApiDispatch } from './http/local-api-dispatch.ts';import { scanGlobalInPlaceSkills, scanInPlaceSkillDirs } from './in-place-skills.ts';import { createLiveDerivedIndexExtension } from './live-derived-index.ts';import { getLogger } from './logger.ts';@@ -409,6 +410,14 @@ export interface ServerInstance {* MUST wire this in, or the ported routes 404 out of the legacy dispatch.*/nativeApi: NativeApiHandle;+ /**+ * In-process `/api/*` dispatch for the MCP tools mounted on this server+ * process (`mcp-http.ts`) — collapses tool self-calls onto the extracted+ * capability services without a TCP round trip. Allowlist-gated inside the+ * api extension; paths outside the collapsed set resolve `null` and the+ * tool falls back to HTTP.+ */+ localApi: LocalApiDispatch;cc1Broadcaster: CC1Broadcaster;agentFocusBroadcaster: AgentFocusBroadcaster;agentPresenceBroadcaster: AgentPresenceBroadcaster;@@ -1059,6 +1068,7 @@ export function createServer(options: ServerOptions): ServerInstance {// `mountMcpAndApi` (and the Vite dev plugin) so the Hono app can claim the// ported paths ahead of the strangler catch-all.let nativeApi: NativeApiHandle;+ let localApi: LocalApiDispatch;// Set at boot when the loss detector is enabled; shared by the agent-session// manager (agent-undo) and the file-watcher intake path (dirty-open-doc).let bridgeLossReporter: BridgeDeriveLossReporter | undefined;@@ -1953,6 +1963,7 @@ export function createServer(options: ServerOptions): ServerInstance {});hocuspocus.configuration.extensions.push(apiExtension);nativeApi = apiExtension.nativeApi;+ localApi = apiExtension.localApi;// Bridge loss-hardening wiring: resolve the defer-guard kill-switch// and construct the content-free loss ring once at boot. Reading the@@ -4603,6 +4614,7 @@ export function createServer(options: ServerOptions): ServerInstance {durabilityState,sessionManager,nativeApi,+ localApi,cc1Broadcaster,agentFocusBroadcaster,agentPresenceBroadcaster,