feat(mcp): compact input schema profile for size-capped providers (kimi-cli/Moonshot) (#1514)

* feat(mcp): add compact input schema profile for size-capped providers

Moonshot's function-calling API rejects a request while any single tool
parameters schema exceeds its literal serialized size cap, so clients
such as kimi-cli fail every request while the default catalog is
attached (#1484).

Add an opt-in REA_MCP_INPUT_SCHEMA_PROFILE=compact server presentation.
Each advertised input schema is rendered within a 13,312-byte budget,
measured to sit below the observed provider cap: annotation prose
(nested descriptions, examples, defaults, titles) is dropped, repeated
annotation-free subschemas are shared through schema-local $defs/$ref
references the provider validates without expansion, and the three
structurally oversized schemas are advertised in a documented reduced
form. The canonical catalog, tool set, output schemas, and server-side
canonical validation are unchanged; the default full profile is
byte-identical to today's advertisement.

Boundary tests pin every compact schema to the budget, keep them valid
JSON Schema that still accepts every canonical example, hold reduced
presentations at three or fewer, and verify canonical rejection still
guards a permissive advertisement. Verified against the real Moonshot
API through kimi-cli: prompts succeed with the compact catalog attached
where the default catalog fails every request with 400.

* fix(mcp): preserve compact schemas through Kimi conversion

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Haythem Sellami
2026-10-10 16:58:43 +08:00
committed by GitHub
co-authored by morluto
parent 2b6f14f528
commit b6ad1f2c3d
15 changed files with 1190 additions and 18 deletions
+76
View File
@@ -5,14 +5,22 @@ import {
isJSONRPCNotification,
isJSONRPCResultResponse,
type Implementation,
type Icon,
type JSONRPCMessage,
type McpServerOptions,
type RegisteredTool,
type RequestId,
type ScopeChallengeHandler,
type StandardSchemaWithJSON,
type ToolAnnotations,
type ToolCallback,
type Transport,
type TransportSendOptions,
} from "@modelcontextprotocol/server";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
import { compactAdvertisedInputSchema } from "../contracts/compactInputSchema.js";
import { transformAdvertisedInputJsonSchema } from "../contracts/toolSchemaMetadata.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
@@ -21,6 +29,24 @@ import { jsonObjectSchema } from "../domain/jsonValue.js";
import type { ToolResultDelivery } from "./toolResult.js";
import { encodeToolResult } from "./toolResultEncoding.js";
/** Compact advertised input schemas within this per-schema byte budget. */
export interface CompactInputSchemaPresentation {
readonly budgetBytes: number;
}
/** A Zod schema whose standard interface exposes a JSON Schema projection. */
const hasAdvertisedInputJsonSchema = (value: unknown): boolean => {
if (typeof value !== "object" || value === null) return false;
const standard = Reflect.get(value, "~standard");
if (typeof standard !== "object" || standard === null) return false;
const jsonSchema = Reflect.get(standard, "jsonSchema");
return (
typeof jsonSchema === "object" &&
jsonSchema !== null &&
Reflect.get(jsonSchema, "input") !== undefined
);
};
/** Bind oversized MCP error recovery to this server's Evidence ledger. */
export class EvidenceMcpServer extends McpServer {
constructor(
@@ -30,10 +56,60 @@ export class EvidenceMcpServer extends McpServer {
| EvidenceWriter["recordEvidence"]
| undefined,
readonly delivery: ToolResultDelivery,
private readonly compactPresentation:
| CompactInputSchemaPresentation
| undefined = undefined,
) {
super(info, options);
}
/**
* Compact the advertised input schema of every registered tool when the
* compact profile is active. The registered canonical schema, its parser,
* and output schemas are untouched; only the advertised JSON Schema
* projection is rendered within the provider's per-schema size budget.
* The signatures mirror the SDK's registrations so call sites keep their
* inferred handler argument types.
*/
override registerTool<
OutputArgs extends StandardSchemaWithJSON,
InputArgs extends StandardSchemaWithJSON | undefined = undefined,
>(
name: string,
config: {
title?: string;
description?: string;
inputSchema?: InputArgs;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
icons?: Icon[];
scopeChallenge?: ScopeChallengeHandler;
_meta?: Record<string, unknown>;
},
callback: ToolCallback<InputArgs>,
): RegisteredTool {
const budget = this.compactPresentation?.budgetBytes;
const inputSchema =
budget !== undefined &&
config !== undefined &&
hasAdvertisedInputJsonSchema(config.inputSchema)
? transformAdvertisedInputJsonSchema(
config.inputSchema as Parameters<
typeof transformAdvertisedInputJsonSchema
>[0],
(projected) =>
compactAdvertisedInputSchema(projected, budget).schema,
)
: undefined;
return super.registerTool(
name,
(inputSchema === undefined
? config
: { ...config, inputSchema }) as never,
callback as never,
);
}
/** Preserve the SDK transport lifecycle while retaining oversized errors. */
override connect(transport: Transport): Promise<void> {
return super.connect(
+24 -1
View File
@@ -15,6 +15,11 @@ import {
type ToolResultDelivery,
} from "./toolResult.js";
import { parseMcpResponseBudget } from "../config/mcpResponseBudget.js";
import {
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
parseMcpInputSchemaProfile,
} from "../config/mcpInputSchemaProfile.js";
import type { CompactInputSchemaPresentation } from "./EvidenceMcpServer.js";
import { isAbsolute } from "node:path";
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
@@ -148,6 +153,7 @@ const installSessionToolAvailability = (
const createMcpServer = (
session: BinarySessionPort | undefined,
delivery: ToolResultDelivery,
compactPresentation: CompactInputSchemaPresentation | undefined,
): EvidenceMcpServer =>
new EvidenceMcpServer(
{
@@ -165,6 +171,7 @@ const createMcpServer = (
? undefined
: (evidence) => session.recordEvidence(evidence),
delivery,
compactPresentation,
);
/**
@@ -183,7 +190,11 @@ export const createServer = (
const selectedOptions = { ...options, environment, delivery };
const startedAt = new Date().toISOString();
const logger = options.logger ?? silentLogger;
const server = createMcpServer(session, delivery);
const server = createMcpServer(
session,
delivery,
selectCompactInputSchemaPresentation(environment),
);
const android =
options.androidAnalysis ?? createAndroidAnalysisProvider(environment);
const availability = installSessionToolAvailability(
@@ -256,6 +267,18 @@ const selectToolResultDelivery = (
return createToolResultDelivery(configured.value);
};
const selectCompactInputSchemaPresentation = (
environment: Readonly<NodeJS.ProcessEnv>,
): CompactInputSchemaPresentation | undefined => {
const configured = parseMcpInputSchemaProfile(
environment.REA_MCP_INPUT_SCHEMA_PROFILE,
);
if (!configured.ok) throw configured.error;
return configured.value === "compact"
? { budgetBytes: COMPACT_INPUT_SCHEMA_BUDGET_BYTES }
: undefined;
};
const registerConfiguredAnalysisTools = (
{
server,