Context7 Platform -- Up-to-date docs for AI agents
CTX7-3290: Admin MCP fixes from live write flows (#3521)
Enes Gules4292e867e88f
diff --git a/packages/admin-mcp/src/server.ts b/packages/admin-mcp/src/server.tsindex d0314fa4..98973710 100644--- a/packages/admin-mcp/src/server.ts+++ b/packages/admin-mcp/src/server.ts@@ -55,7 +55,9 @@ function createApi(state: RequestState): Api {// (expired, revoked, or issued for another resource). Set before the body// is read, so a failed read still ends in the OAuth challenge.if (response.status === 401) state.authRejected = true;- const text = await response.text();+ // A broken error body must not hide the status, which decides the outcome;+ // a broken success body is a failure of its own.+ const text = response.ok ? await response.text() : await response.text().catch(() => "");let parsed: unknown = text;try {parsed = text ? JSON.parse(text) : null;@@ -112,6 +114,8 @@ const NEXT_STEP: Record<string, string> = {run_in_progress: "A run is already in progress. Wait for it with docs7_get_agent_runs.",project_busy: "The teamspace is changing. Try again in a few seconds.",ambiguous_version: "Set is_branch to true or false.",+ library_not_found:+ "The teamspace has no such library. Suggestions, benchmarks, analytics and config need a library the teamspace owns (list_libraries); claim_library claims a public one.",};function nextStep(status: number, body: unknown): string | undefined {diff --git a/packages/admin-mcp/src/tools.ts b/packages/admin-mcp/src/tools.tsindex 5edaa698..e26dc84d 100644--- a/packages/admin-mcp/src/tools.ts+++ b/packages/admin-mcp/src/tools.ts@@ -190,19 +190,44 @@ type AgentRun = {pullRequest?: { state?: unknown };};+/** The agents whose runs each agent-runs history holds. */+const HISTORY_AGENTS = {+ improve: ["context7", "buildFix"],+ review: ["prReview"],+ watch: ["codeWatch"],+} as const;+type AgentHistory = keyof typeof HISTORY_AGENTS;++/** The most runs the agent-runs route gives per history. */+export const AGENT_HISTORY_LIMIT = 50;+/*** This UTC month's runs of each agent and the states of their pull requests,* read from the newest 50 runs of each history, as the dashboard's Agents card- * counts them. Superseded runs are left out, as there.+ * counts them. Superseded runs are left out, as there. When a full history+ * starts inside the month, older runs of the month are not read: its agents+ * are named in `minimumCounts`.*/-export function agentActivity(histories: AgentRun[][], now = new Date()): Record<string, unknown> {+export function agentActivity(+ histories: Record<AgentHistory, AgentRun[]>,+ now = new Date()+): Record<string, unknown> {const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1);+ const inMonth = (run: AgentRun) =>+ typeof run.createdAt === "string" && Date.parse(run.createdAt) >= monthStart;+ const minimumCounts = new Set<string>();+ for (const history of Object.keys(HISTORY_AGENTS) as AgentHistory[]) {+ const list = histories[history];+ if (list.length >= AGENT_HISTORY_LIMIT && list.every(inMonth)) {+ // An agent can be missing from the window and still have older runs this month.+ for (const agent of HISTORY_AGENTS[history]) minimumCounts.add(agent);+ }+ }const runs: Record<string, number> = {};const failedRuns: Record<string, number> = {};const pullRequests: Record<string, Record<string, number>> = {};- for (const run of histories.flat()) {- if (run.state === "superseded") continue;- if (typeof run.createdAt !== "string" || Date.parse(run.createdAt) < monthStart) continue;+ for (const run of Object.values(histories).flat()) {+ if (run.state === "superseded" || !inMonth(run)) continue;const agent = runAgent(run);runs[agent] = (runs[agent] ?? 0) + 1;if (run.state === "failed") failedRuns[agent] = (failedRuns[agent] ?? 0) + 1;@@ -212,7 +237,13 @@ export function agentActivity(histories: AgentRun[][], now = new Date()): Recordcounts[state] = (counts[state] ?? 0) + 1;}}- return { month: new Date(monthStart).toISOString().slice(0, 7), runs, failedRuns, pullRequests };+ return {+ month: new Date(monthStart).toISOString().slice(0, 7),+ runs,+ failedRuns,+ pullRequests,+ minimumCounts: minimumCounts.size ? [...minimumCounts] : undefined,+ };}const RUN_NOISE = new Set(["boxId", "siteId"]);@@ -298,6 +329,28 @@ function data(body: unknown): Record<string, unknown> {return value && typeof value === "object" ? (value as Record<string, unknown>) : {};}+/**+ * The library a rule belongs to, or null for a teamspace rule: as given, else+ * looked up in the rule list, since the API finds a library rule only by both ids.+ */+async function ruleLibrary(+ api: Api,+ base: string,+ ruleId: string,+ given: string | undefined+): Promise<string | null> {+ if (given) return normalizeLibraryId(given);+ const { libraries = {} } = data(await api.get(base)) as {+ libraries?: Record<string, Record<string, unknown>>;+ };+ return Object.keys(libraries).find((library) => ruleId in libraries[library]) ?? null;+}++/** The filter mode a library request's list works in: allow lists are `select`, the rest `quality`. */+function requestMode(requestType: unknown): "select" | "quality" {+ return requestType === "allow" || requestType === "unallow" ? "select" : "quality";+}+/** The email of the member with this id, from `GET /members` (`{ members, invitations }`). */function memberEmail(body: unknown, memberId: string): string | undefined {const { members } = (body ?? {}) as { members?: { id?: unknown; email?: unknown }[] };@@ -681,7 +734,7 @@ export const TOOLS: ToolDef[] = [.string().optional().describe(- "Library id of a library rule (create, update, delete). Leave out for a teamspace rule."+ "Library id of a library rule (create). Leave out for a teamspace rule. Update and delete find the rule's library from `rule_id`."),confirm: z.string()@@ -706,16 +759,16 @@ export const TOOLS: ToolDef[] = [return data(await api.patch(`${base}/${ruleId()}`, {text: need(args.text, "`text` is required."),- libraryId: args.library_id ? normalizeLibraryId(args.library_id) : null,+ libraryId: await ruleLibrary(api, base, args.rule_id!, args.library_id),}));- default:+ default: {confirmed(args.confirm, need(args.rule_id, "`rule_id` is required."), "the rule id");+ const libraryId = await ruleLibrary(api, base, args.rule_id!, args.library_id);return data(- await api.del(`${base}/${ruleId()}`, {- query: { libraryId: args.library_id && normalizeLibraryId(args.library_id) },- })+ await api.del(`${base}/${ruleId()}`, { query: { libraryId: libraryId ?? undefined } }));+ }}},}),@@ -789,7 +842,7 @@ export const TOOLS: ToolDef[] = [if ((library_filters?.quality || library_filters?.select) && !result?.libraryFilters?.mode) {return {...result,- note: 'Library filters are off (mode is null), so these rules change nothing. Set `library_filters.mode` to "quality" or "select" to apply them.',+ note: 'Library filters are off (mode is null): the saved rules have no effect until `library_filters.mode` is "quality" or "select".',};}return result;@@ -814,7 +867,7 @@ export const TOOLS: ToolDef[] = [.describe("What to request (request)."),request_id: z.string().optional().describe("Request id from list (approve, dismiss)."),},- run: (args, api) => {+ run: async (args, api) => {const base = `${ts(args.teamspace)}/library-requests`;const requestId = () => seg(need(args.request_id, "`request_id` is required."));switch (args.action) {@@ -825,8 +878,31 @@ export const TOOLS: ToolDef[] = [libraryIdentifier: need(args.library, "`library` is required."),requestType: need(args.request_type, "`request_type` is required."),});- case "approve":- return api.post(`${base}/${requestId()}/approve`);+ case "approve": {+ // Approval edits a list, never the mode, so the mode is read first: a+ // rejected credential then stops the call before anything is written.+ const policies = (await api+ .get(`${ts(args.teamspace)}/policies`)+ .then(data)+ .catch((error: unknown) => {+ if (error instanceof Error && "status" in error && error.status === 401) throw error;+ return null;+ })) as { libraryFilters?: { mode?: unknown } } | null;+ const approved = await api.post(`${base}/${requestId()}/approve`);+ // The list applies only in its own filter mode.+ const mode = requestMode(data(approved).requestType);+ if (policies?.libraryFilters?.mode === mode) return approved;+ if (!policies) {+ return {+ ...data(approved),+ note: `Approved. Could not read the policies to check that library filters are in "${mode}" mode; the list has no effect in another mode. Check with get_library_policies, and ask the user before you change the mode.`,+ };+ }+ return {+ ...data(approved),+ note: `Saved in the policy list, but library filters are not in "${mode}" mode, so it has no effect yet. Ask the user before you call update_library_policies with \`library_filters.mode: "${mode}"\`: that mode changes which libraries the whole teamspace can use (try \`dry_run: true\` first).`,+ };+ }default:return api.del(`${base}/${requestId()}`);}@@ -892,14 +968,20 @@ export const TOOLS: ToolDef[] = [const details = data(await api.get(path));// A CLI site has no agent, and its agent-usage route answers 404.if (details.source === "local") return { site: siteDetails(details) };- const [usage, ...histories] = await Promise.all([+ const readHistory = async (history: AgentHistory) =>+ (+ (await api.get(`${path}/agent-runs`, { history, limit: AGENT_HISTORY_LIMIT })) as {+ data?: AgentRun[];+ }+ )?.data ?? [];+ const [usage, improve, review, watch] = await Promise.all([api.get(`${path}/agent-usage`),- ...["improve", "review", "watch"].map((history) =>- api.get(`${path}/agent-runs`, { history, limit: 50 })- ),+ readHistory("improve"),+ readHistory("review"),+ readHistory("watch"),]);- const runs = histories.map((body) => (body as { data?: AgentRun[] })?.data ?? []);- return { site: siteDetails(details), agentUsage: { ...data(usage), ...agentActivity(runs) } };+ const activity = agentActivity({ improve, review, watch });+ return { site: siteDetails(details), agentUsage: { ...data(usage), ...activity } };},}),tool({@@ -926,8 +1008,8 @@ export const TOOLS: ToolDef[] = [custom_domain_routing: z.enum(["dns", "proxy"]).optional(),context7_index: z.boolean().optional().describe("Also index the site in Context7."),},- run: (args, api) =>- api.post(`${ts(args.teamspace)}/sites`, {+ run: async (args, api) => {+ const created = (await api.post(`${ts(args.teamspace)}/sites`, {repoUrl: args.repo_url,docsPath: args.docs_path,branch: args.branch,@@ -936,7 +1018,9 @@ export const TOOLS: ToolDef[] = [customDomainPath: args.custom_domain_path,customDomainRouting: args.custom_domain_routing,context7Index: args.context7_index,- }),+ })) as { data?: Record<string, unknown>; deploymentId?: unknown };+ return { site: siteDetails(data(created)), deploymentId: created?.deploymentId ?? null };+ },}),tool({name: "docs7_update_site",@@ -985,8 +1069,8 @@ export const TOOLS: ToolDef[] = [.optional().describe("All Code Watch settings: the full list of watched repositories."),},- run: ({ teamspace, site_id, ...fields }, api) => {- return api.patch(site(teamspace, site_id), {+ run: async ({ teamspace, site_id, ...fields }, api) => {+ const updated = await api.patch(site(teamspace, site_id), {slug: fields.slug,branch: fields.branch,docsPath: fields.docs_path,@@ -1001,6 +1085,7 @@ export const TOOLS: ToolDef[] = [pullRequestReview: fields.pull_request_review,codeWatch: fields.code_watch,});+ return { site: siteDetails(data(updated)) };},}),tool({diff --git a/packages/admin-mcp/test/admin-mcp.test.ts b/packages/admin-mcp/test/admin-mcp.test.tsindex d7d8210a..7db4b954 100644--- a/packages/admin-mcp/test/admin-mcp.test.ts+++ b/packages/admin-mcp/test/admin-mcp.test.ts@@ -418,15 +418,17 @@ test("the server card and serverInfo carry the Context7 icon", async () => {test("agent usage counts this UTC month's runs by agent, without superseded runs", () => {const now = new Date("2026-10-22T12:00:00Z");const usage = agentActivity(- [- [+ {+ improve: [{ state: "completed", createdAt: "2026-10-02T00:00:00Z", pullRequest: { state: "merged" } },{ state: "completed", createdAt: "2026-10-04T00:00:00Z", pullRequest: { state: "open" } },{ state: "failed", createdAt: "2026-10-03T00:00:00Z", input: { kind: "health" } },{ state: "completed", createdAt: "2026-09-30T23:59:59Z", pullRequest: { state: "open" } },],- [{ state: "superseded", createdAt: "2026-10-05T00:00:00Z", input: { kind: "review" } }],- [+ review: [+ { state: "superseded", createdAt: "2026-10-05T00:00:00Z", input: { kind: "review" } },+ ],+ watch: [{state: "completed",createdAt: "2026-10-21T00:00:00Z",@@ -434,7 +436,7 @@ test("agent usage counts this UTC month's runs by agent, without superseded runspullRequest: { state: "open" },},],- ],+ },now);expect(usage).toEqual({@@ -491,3 +493,97 @@ test("get_library_benchmarks gives the lowest scores first", async () => {expect(body.benchmarks.map((b: { query: string }) => b.query)).toEqual(["b", "c"]);expect(apiCalls[0].path).toBe(`/v2/teamspaces/${TS}/libraries/acme/docs/benchmarks`);});++// The API finds a library rule only with its library id, which agents leave out.+test("manage_rules delete finds the library of a library rule", async () => {+ apiReply = (call) => ({+ body:+ call.method === "GET"+ ? { success: true, data: { global: {}, libraries: { "/vercel/next.js": { r1: {} } } } }+ : { success: true },+ });+ const result = await (+ await connect()+ ).callTool({+ name: "manage_rules",+ arguments: { teamspace: TS, action: "delete", rule_id: "r1", confirm: "r1" },+ });+ expect(result.isError).toBeFalsy();+ expect(apiCalls.at(-1)).toMatchObject({+ method: "DELETE",+ path: `/v2/teamspaces/${TS}/rules/r1?libraryId=%2Fvercel%2Fnext.js`,+ });+});++test("approving a request says when its filter mode is off", async () => {+ apiReply = (call) => ({+ body: call.path.endsWith("/approve")+ ? { data: { id: "block:/vercel/next.js", requestType: "block" } }+ : { libraryFilters: { quality: { blockedLibraries: ["/vercel/next.js"] } } },+ });+ const result = await (+ await connect()+ ).callTool({+ name: "manage_library_requests",+ arguments: { teamspace: TS, action: "approve", request_id: "block:/vercel/next.js" },+ });+ expect(text(result)).toContain('not in \\"quality\\" mode');+});++test("agent usage names the agents whose history may hold more runs this month", () => {+ const full = Array.from({ length: 50 }, () => ({+ state: "completed",+ createdAt: "2026-10-20T00:00:00Z",+ input: { kind: "review" },+ }));+ const usage = agentActivity(+ {+ improve: full.map((run) => ({ ...run, input: { kind: "suggestions" } })),+ review: full,+ watch: [],+ },+ new Date("2026-10-22T00:00:00Z")+ );+ // Build Fix shares the improve history: not in the window, still possibly undercounted.+ expect(usage).toMatchObject({+ runs: { context7: 50, prReview: 50 },+ minimumCounts: ["context7", "buildFix", "prReview"],+ });+});++test("approve reads the policies first, so a rejected credential writes nothing", async () => {+ apiReply = (call) =>+ call.path.endsWith("/policies")+ ? { status: 401, body: { error: "invalid_api_key" } }+ : { body: {} };+ const client = await connect();+ await expect(+ client.callTool({+ name: "manage_library_requests",+ arguments: { teamspace: TS, action: "approve", request_id: "block:/vercel/next.js" },+ })+ ).rejects.toThrow(/invalid_token/);+ expect(apiCalls.some((call) => call.path.endsWith("/approve"))).toBe(false);+ expect(lastResponse?.status).toBe(401);+});++test("a 401 whose body cannot be read still stops the approval", async () => {+ vi.stubGlobal("fetch", async (input: URL | string, init?: RequestInit) => {+ const path = new URL(input).pathname;+ apiCalls.push({ method: init?.method ?? "GET", path, body: undefined });+ const broken = new ReadableStream({+ start: (controller) => controller.error(new Error("reset")),+ });+ return path.endsWith("/policies")+ ? new Response(broken, { status: 401 })+ : Response.json({ data: {} });+ });+ const client = await connect();+ await expect(+ client.callTool({+ name: "manage_library_requests",+ arguments: { teamspace: TS, action: "approve", request_id: "block:/vercel/next.js" },+ })+ ).rejects.toThrow(/invalid_token/);+ expect(apiCalls.some((call) => call.path.endsWith("/approve"))).toBe(false);+});