Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .oxfmtrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"packages/cli/CONTRIBUTING.md",
"packages/cli/CHANGELOG.md",
"packages/cli/AGENTS.md",
"packages/mcp-core/src/command-catalog.json",
"packages/mcp-server-mocks/src/fixtures/**",
"packages/codemod-cli3to4/tests/**",
"**/worker-configuration.d.ts",
Expand Down
9 changes: 9 additions & 0 deletions packages/cli/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,15 @@ and any declared `permission` into the command's permission class, and
`check:command-access` fails when a declaration contradicts the requests or
a command declares no exposure.

`generate:command-catalog` (part of `generate:docs`) writes
`packages/mcp-core/src/command-catalog.json` from the same introspection
(`src/lib/command-catalog.ts`): for each command whose exposure is not
`hidden`, its permission class, exposure, parameters as JSON Schema,
completion kinds, local-path flags, examples, output fields, and API
operations. MCP servers import it from `@sentry/mcp-core/command-catalog`
and read it instead of building schemas at runtime. The file is committed;
`check:command-catalog` (in `ci:policy`) fails when it is stale.

Introspection derives canonical command paths, registered aliases, and group
membership from the route tree. Groups collect their public commands' generated
references, so adding a command requires no separate group mapping. A related API
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"generate:docs-sections": "tsx script/generate.ts docs-sections",
"generate:schema": "tsx script/generate.ts schema",
"generate:command-api": "tsx script/generate.ts command-api",
"generate:command-catalog": "tsx script/generate.ts command-catalog",
"generate:command-docs": "tsx script/generate.ts command-docs",
"eval:skill": "pnpm tsx script/eval-skill.ts",
"bench": "pnpm tsx script/bench.ts",
Expand All @@ -96,7 +97,8 @@
"check:installer-docs": "pnpm tsx script/check-installer-docs.ts",
"check:destructive": "pnpm tsx script/check-destructive-commands.ts",
"check:command-access": "pnpm tsx script/check-command-access.ts",
"ci:policy": "pnpm run check:patches && pnpm run check:deps && pnpm run check:errors && pnpm run check:fragments && pnpm run check:docs-sections && pnpm run check:env-coverage && pnpm run check:stale-refs && pnpm run check:doc-examples && pnpm run check:installer-docs && pnpm run check:destructive && pnpm run check:command-access"
"check:command-catalog": "tsx script/generate.ts command-catalog --check",
"ci:policy": "pnpm run check:patches && pnpm run check:deps && pnpm run check:errors && pnpm run check:fragments && pnpm run check:docs-sections && pnpm run check:env-coverage && pnpm run check:stale-refs && pnpm run check:doc-examples && pnpm run check:installer-docs && pnpm run check:destructive && pnpm run check:command-access && pnpm run check:command-catalog"
},
"devDependencies": {
"@anthropic-ai/sdk": "^0.39.0",
Expand Down
58 changes: 58 additions & 0 deletions packages/cli/script/generate-command-catalog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* Generate `command-catalog.json` (`src/lib/command-catalog.ts`) for the MCP
* servers, which read it instead of building schemas at runtime. It is
* written to mcp-core, where mcp-cloudflare can import it, and committed, so
* `--check` fails when it is stale.
*
* It runs after `command-api` in `script/generate.ts`, so it reads that
* step's output from disk: the route tree's own imports of those files were
* stubs or the previous run's when the tree loaded.
*/

import { readFile, writeFile } from "node:fs/promises";
import { routes } from "../src/app.js";
import type { ApiReference } from "../src/lib/api-schema.js";
import type { ApiAccess } from "../src/lib/command-access.js";
import { extractCommandCatalog } from "../src/lib/command-catalog.js";
import type { RouteMap } from "../src/lib/introspect.js";

const COMMAND_CATALOG_PATH = "../mcp-core/src/command-catalog.json";

async function readJson<T>(path: string): Promise<T> {
return JSON.parse(await readFile(path, "utf8")) as T;
}

/** Write the catalog, or with `check`, exit 1 when the committed one is stale. */
export async function emit({ check }: { check: boolean }): Promise<void> {
const catalog = extractCommandCatalog(
routes as unknown as RouteMap,
await readJson<Record<string, ApiReference[]>>(
"src/generated/command-api.json",
),
await readJson<Record<string, ApiAccess>>(
"src/generated/command-api-access.json",
),
);
const content = `${JSON.stringify(catalog, null, 2)}\n`;

if (check) {
const current = await readFile(COMMAND_CATALOG_PATH, "utf8").catch(
() => "",
);
if (current !== content) {
console.error(
`✗ ${COMMAND_CATALOG_PATH} is stale. Run \`pnpm run generate:command-catalog\` in packages/cli and commit the result.`,
);
process.exitCode = 1;
} else {
console.log(
`✓ ${COMMAND_CATALOG_PATH} is up to date (${catalog.commands.length} commands)`,
);
}
return;
}
await writeFile(COMMAND_CATALOG_PATH, content);
console.log(
`Generated ${COMMAND_CATALOG_PATH} (${catalog.commands.length} commands)`,
);
}
11 changes: 8 additions & 3 deletions packages/cli/script/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,16 +194,21 @@ const TREE_STEPS: readonly Step[] = [
{ name: "docs-sections", load: () => import("./generate-docs-sections.js") },
{ name: "skill", load: () => import("./generate-skill.js") },
{ name: "sdk", load: () => import("./generate-sdk.js") },
// Last: its emit waits for the worker `prepare` starts, and no step reads
// `command-api.json` or `command-api-access.json` back (only the CLI does,
// at runtime).
// Late: its emit waits for the worker `prepare` starts. Only
// `command-catalog` reads its output back.
{
name: "command-api",
load: () => import("./generate-command-api.js"),
prepare: (after) => {
void commandApiAnalysis(after("schema"));
},
},
// Reads `command-api.json` and `command-api-access.json` from disk, so it
// runs after `command-api`.
{
name: "command-catalog",
load: () => import("./generate-command-catalog.js"),
},
];

const STEP_NAMES = [...PRE_TREE_STEPS, ...TREE_STEPS].map((step) => step.name);
Expand Down
204 changes: 204 additions & 0 deletions packages/cli/src/lib/command-catalog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
/**
* The command catalog: what agents need to find and run each command, from
* the route tree's introspection. Build-time only: `generate:command-catalog`
* writes it to `@sentry/mcp-core/command-catalog`, and MCP servers read that
* generated JSON instead of building schemas at runtime.
*
* Commands with exposure `hidden` are left out: no MCP server lists them.
*/

import type {
CommandCatalog,
CommandCatalogEntry,
JsonSchema,
} from "@sentry/mcp-core/command-catalog";
import generatedCommandApi from "../generated/command-api.json";
import type { ApiReference } from "./api-schema.js";
import type { ApiAccess } from "./command-access.js";
import { CHOICE_TARGET } from "./completion-target.js";
import {
argumentCompletion,
buildCommandInfo,
type Command,
type FlagDef,
isCommand,
type PositionalParam,
publicTargetPaths,
type RouteMap,
} from "./introspect.js";

/**
* Type of one positional or flag value. Only Stricli `enum` flags reject
* other values; the values of a `choice` parser are suggestions.
*/
function valueSchema(
def: Pick<FlagDef, "parse" | "placeholder" | "default">,
enumValues?: readonly string[],
): JsonSchema {
if (enumValues) {
return { type: "string", enum: [...enumValues] };
}
const { kind, values } = argumentCompletion(def.parse);
if (kind === CHOICE_TARGET && values) {
return { type: "string", examples: [...values] };
}
// The same inference as the generated SDK's parameter types.
const numeric =
def.placeholder === "number" ||
typeof def.default === "number" ||
(typeof def.default === "string" &&
def.default !== "" &&
!Number.isNaN(Number(def.default)));
return { type: numeric ? "number" : "string" };
}

/** JSON Schema of one flag. */
function flagSchema(def: FlagDef): JsonSchema {
const value: JsonSchema =
def.kind === "boolean"
? { type: "boolean" }
: valueSchema(def, def.kind === "enum" ? def.values : undefined);
const schema: JsonSchema = def.variadic
? { type: "array", items: value }
: value;
if (def.brief) schema.description = def.brief;
if (def.default !== undefined) {
schema.default =
value.type === "number" ? Number(def.default) : def.default;
}
return schema;
}

/** JSON Schema of one positional. */
function positionalSchema(param: PositionalParam, index: number): JsonSchema {
return {
...valueSchema(param),
title: param.placeholder ?? `arg${index}`,
...(param.brief ? { description: param.brief } : {}),
};
}

/** JSON Schema of a command's positionals and visible flags. */
function parametersSchema(command: Command): JsonSchema {
const { positional, flags = {} } = command.parameters;
const properties: Record<string, JsonSchema> = {};
const required: string[] = [];

if (positional?.kind === "tuple" && positional.parameters.length > 0) {
const minItems = positional.parameters.filter((p) => !p.optional).length;
properties.positional = {
type: "array",
prefixItems: positional.parameters.map(positionalSchema),
items: false,
...(minItems > 0 ? { minItems } : {}),
};
if (minItems > 0) required.push("positional");
} else if (positional?.kind === "array") {
properties.positional = {
type: "array",
items: positionalSchema(positional.parameter, 0),
};
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
}

const flagProperties: Record<string, JsonSchema> = {};
const requiredFlags: string[] = [];
for (const [name, def] of Object.entries(flags)) {
if (def.hidden) continue;
flagProperties[name] = flagSchema(def);
const optional = def.optional ?? def.kind === "boolean";
if (!optional && def.default === undefined) requiredFlags.push(name);
}
if (Object.keys(flagProperties).length > 0) {
properties.flags = {
type: "object",
properties: flagProperties,
...(requiredFlags.length > 0 ? { required: requiredFlags } : {}),
additionalProperties: false,
};
if (requiredFlags.length > 0) required.push("flags");
}

return {
type: "object",
properties,
...(required.length > 0 ? { required } : {}),
additionalProperties: false,
};
}

/** Completion kinds of a command's positionals and visible flags. */
function completions(command: Command): CommandCatalogEntry["completions"] {
const { positional, flags = {} } = command.parameters;
const params =
positional?.kind === "tuple"
? positional.parameters
: positional
? [positional.parameter]
: [];
const positionalKinds = params.map(
(param) => argumentCompletion(param.parse).kind,
);
const flagKinds: Record<string, string> = {};
for (const [name, def] of Object.entries(flags)) {
if (def.hidden || def.kind === "boolean") continue;
const { kind } = argumentCompletion(
def.parse,
def.kind === "enum" ? def.values : undefined,
);
if (kind) flagKinds[name] = kind;
}
const result: CommandCatalogEntry["completions"] = {
...(positionalKinds.some((kind) => kind !== null)
? { positional: positionalKinds }
: {}),
...(Object.keys(flagKinds).length > 0 ? { flags: flagKinds } : {}),
};
return Object.keys(result).length > 0 ? result : undefined;
}

/**
* Build the catalog of every command an MCP server may list: each public
* command whose exposure is not `hidden`, sorted by path.
*
* @param routeMap - Top-level Stricli route map
* @param apiByCommand - API references by command path (`command-api.json`)
* @param apiAccessByCommand - API request class by command path
* (`command-api-access.json`); introspection's import when omitted
*/
export function extractCommandCatalog(
routeMap: RouteMap,
apiByCommand: Readonly<
Record<string, readonly ApiReference[]>
> = generatedCommandApi,
apiAccessByCommand?: Readonly<Record<string, ApiAccess>>,
): CommandCatalog {
const commands: CommandCatalogEntry[] = [];
for (const [command, segments] of publicTargetPaths(routeMap)) {
if (!isCommand(command)) continue;
const info = buildCommandInfo(
command,
`sentry ${segments.join(" ")}`,
apiAccessByCommand,
);
const { exposure } = info;
if (exposure === "hidden") continue;
const localPathFlags = info.flags
.filter((flag) => flag.localPath && !flag.hidden)
.map((flag) => flag.name);
const completion = completions(command);
commands.push({
path: info.path,
brief: info.brief,
permission: info.permission,
exposure,
parameters: parametersSchema(command),
...(completion ? { completions: completion } : {}),
...(localPathFlags.length > 0 ? { localPathFlags } : {}),
examples: info.examples,
...(info.jsonFields ? { outputFields: info.jsonFields } : {}),
apiOperations: [...(apiByCommand[info.path] ?? [])],
});
}
commands.sort((a, b) => a.path.localeCompare(b.path));
return { commands };
}
2 changes: 1 addition & 1 deletion packages/cli/src/lib/introspect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ export type CommandCompletions = Record<string, CommandCompletion>;
* The kind and, for `choice` and `choice-list`, the values of one
* argument: those of an `enum` flag, or the ones its parser completes.
*/
function argumentCompletion(
export function argumentCompletion(
parse: unknown,
enumValues?: readonly string[],
): { kind: CompletionTarget | null; values?: readonly string[] } {
Expand Down
Loading
Loading