Files
reverse-engineering-anything/src/server/ProgressiveToolCatalog.ts
T
Deepak Jain (DJ) fd40fd9ab2 fix(mcp): accept discover_tools in exact-name discovery batches (#13288)
With REA_MCP_TOOL_CATALOG_PROFILE=hot-cold, discover_tools is listed in
tools/list, yet an exact-name request that named it failed with "Unknown
or excluded tool names. No tools were loaded." Exact names load
atomically, so a batch such as ["inspect_sqlite_database",
"discover_tools"] also left the valid cold tool unloaded.

The catalog validated names against the domain registrations it was
built from, and the server registered the adapter only after building
it. The server now registers discover_tools first and passes that
registration to ProgressiveToolCatalog. Exact-name lookup, the returned
entries and both counts read one inventory that includes the adapter,
which replaces the two "+ 1" adjustments. Search and reset still cover
only domain tools, so a query never spends a page slot on the adapter
and reset never hides it. Unknown or excluded names are still rejected
before anything loads.

Signed-off-by: Deepak Jain <deepujain@gmail.com>
2026-11-21 21:37:07 -05:00

182 lines
6.6 KiB
TypeScript

import type { RegisteredTool } from "@modelcontextprotocol/server";
import type { z } from "zod";
import {
AnalysisInputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { ownedJsonObjectSchema } from "../domain/jsonValue.js";
import { encodeToolResult } from "./toolResultEncoding.js";
import type { ToolResultDelivery } from "./ToolResultDelivery.js";
import {
DISCOVER_TOOLS,
HOT_TOOL_NAMES,
progressiveCatalogIdentity,
type CatalogIdentity,
} from "../contracts/catalog/catalogDiscovery.js";
type CatalogListing = { registered: RegisteredTool; description: string };
const catalogListing = (registered: RegisteredTool): CatalogListing => ({
registered,
description: (registered.description ?? "").slice(0, 240),
});
/** Per-connection visibility; canonical SDK handles retain validation and authority. */
export class ProgressiveToolCatalog {
readonly identity: CatalogIdentity;
/** In-scope domain tools; the adapter is never a search result or reset. */
private readonly tools: ReadonlyMap<
string,
CatalogListing & { search: string }
>;
/** Exact names and counts also cover the always-advertised adapter. */
private readonly inventory: ReadonlyMap<string, CatalogListing>;
constructor(
registrations: ReadonlyMap<string, RegisteredTool>,
adapter: RegisteredTool,
identity: CatalogIdentity,
private readonly batchChanges: (change: () => void) => void,
private readonly delivery: () => ToolResultDelivery,
) {
this.identity = progressiveCatalogIdentity(identity);
// Disabled family registrations are outside the discoverable scope. Never
// let discovery re-enable a tool the caller excluded from this server.
this.tools = new Map(
[...registrations]
.filter(([, tool]) => tool.enabled)
.map(([name, registered]) => [
name,
{
...catalogListing(registered),
search:
`${name} ${name.replaceAll("_", " ")} ${registered.description ?? ""}`.toLowerCase(),
},
]),
);
this.inventory = new Map<string, CatalogListing>([
...this.tools,
[DISCOVER_TOOLS.name, catalogListing(adapter)],
]);
this.reset();
}
/** A reused HTTP server starts each new transport with the hot inventory. */
reset(): void {
this.batchChanges(() => {
for (const [name, { registered }] of this.tools) {
if (registered.enabled && !HOT_TOOL_NAMES.has(name))
registered.disable();
}
});
}
discover(input: z.infer<typeof DISCOVER_TOOLS.inputSchema>) {
const names =
input.names === undefined ? undefined : [...new Set(input.names)];
const unknown = names?.filter((name) => !this.inventory.has(name)) ?? [];
if (unknown.length > 0)
return this.delivery().toErrorToolResult(
new AnalysisInputError(
DISCOVER_TOOLS.name,
{
userMessage:
"Unknown or excluded tool names. No tools were loaded.",
remediationAction:
"Search with query to find exact in-scope names.",
conformsToInputContract: true,
},
unknown.map((name) => ({
path: ["names"],
reason: "invalid_value",
message: name,
})),
),
false,
);
const words = (input.query ?? "")
.toLowerCase()
.split(/\s+/u)
.filter(Boolean);
const matches =
names ??
[...this.tools]
.filter(([, tool]) => words.every((word) => tool.search.includes(word)))
.map(([name]) => name)
.sort((left, right) => {
const score = (name: string) =>
words.filter((word) => name.includes(word)).length;
return (
score(right) - score(left) ||
(left < right ? -1 : left > right ? 1 : 0)
);
});
const page =
names ?? matches.slice(input.offset, input.offset + input.limit);
const selected = page.map((name) => ({
name,
...this.inventory.get(name)!,
}));
const result: z.infer<typeof DISCOVER_TOOLS.outputSchema> = {
profile: "hot-cold",
inventory_count: this.inventory.size,
loaded_count:
[...this.inventory.values()].filter(
({ registered }) => registered.enabled,
).length +
selected.filter(({ registered }) => !registered.enabled).length,
total_matches: matches.length,
next_offset:
names === undefined && input.offset + page.length < matches.length
? input.offset + page.length
: null,
tools: selected.map(({ name, description, registered }) => ({
name,
description,
input_schema: registered.inputSchema?.["~standard"].jsonSchema.input({
target: "draft-2020-12",
}) ?? { type: "object" },
})),
next_step:
selected.length === 0
? matches.length === 0
? "No matches. Try fewer or different task keywords, or browse without query."
: "No remaining matches at this offset. Use offset 0 to restart this query, or select an earlier offset."
: "Call the returned tool by its original name using input_schema. Your client must refresh tools/list first; if it cannot, reconnect with REA_MCP_TOOL_CATALOG_PROFILE=full.",
};
// This reply borrows read-only SDK schema projections for synchronous
// encoding; validate the new reply without copying their complete trees.
const payload = ownedJsonObjectSchema.parse(result);
const delivery = this.delivery();
const encoded = encodeToolResult(payload, delivery.resultBudgetBytes);
if (!encoded.ok)
return delivery.toErrorToolResult(
new AnalysisResourceConstraintError(
DISCOVER_TOOLS.name,
"transport",
"The discovery page exceeds the reply budget. No tools were loaded.",
{
result_budget_bytes: delivery.resultBudgetBytes,
response_bytes_at_least: encoded.bytesAtLeast,
constraint: encoded.constraint,
},
{
remediationAction:
"Reduce limit or request fewer exact names, then retry.",
},
),
false,
);
// Visibility changes only after both reply representations fit. A failed
// page can be retried without silently enabling unreported definitions.
this.batchChanges(() => {
for (const { registered } of selected) {
if (!registered.enabled) registered.enable();
}
});
return {
content: [{ type: "text" as const, text: encoded.text }],
structuredContent: payload,
};
}
}