Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat(docs): make coding agents reach for REST API v3.1 (#4079)

Alberto Schiabel6e0a9db3c7eb
diff --git a/context7.json b/context7.json
index 4c653cb38..735244292 100644
--- a/context7.json
+++ b/context7.json
@@ -13,6 +13,11 @@
"CODE_OF_CONDUCT.md",
"code_of_conduct.md"
],
- "rules": [],
+ "rules": [
+ "The current Composio REST API version is v3.1, served at https://backend.composio.dev/api/v3.1. Prefer it for new code and new examples.",
+ "https://backend.composio.dev/api/v3 is the previous REST API version. It is frozen with pinned tool-version defaults and remains supported — existing v3 integrations keep working and do not need to migrate.",
+ "On v3.1, GET /tools, GET /tools/{tool_slug}, POST /tools/execute/{tool_slug}, POST /tools/execute/{tool_slug}/input, and POST /tools/scopes/required default their version parameter to the latest toolkit version instead of the pinned 00000000_00. Code that needs the v3 pinned default must pass it explicitly: version=00000000_00, or toolkit_versions=00000000_00 on GET /tools. This version-default change is limited to these five endpoints.",
+ "TypeScript (@composio/core) and Python (composio) SDK callers are already on v3.1 through the generated client; this only affects direct REST calls."
+ ],
"previousVersions": []
}
diff --git a/docs/agent-guidance/context/api-reference.md b/docs/agent-guidance/context/api-reference.md
index 3fbeb075f..ad87cddb2 100644
--- a/docs/agent-guidance/context/api-reference.md
+++ b/docs/agent-guidance/context/api-reference.md
@@ -92,6 +92,59 @@ components/api-endpoints-table.tsx ← Endpoint tables in index pages, shows ver
components/version-badge.tsx ← Badge on endpoint pages showing API version
```
+Markdown channels (what agents read — see "Version identity in the markdown
+channels" below):
+
+```
+lib/source.ts ← mdxToCleanMarkdown renders ApiBaseUrl + ApiEndpointsTable for .md
+app/llms.mdx/[[...slug]]/route.ts ← openapiPageToMarkdown emits the version pointer + guidance
+lib/api-endpoints-table-schema.ts ← shared zod schema for the ApiEndpointsTable prop
+lib/api-version-guidance.ts ← the two guidance constants + the tool-path predicate
+```
+
+### Version identity in the markdown channels
+
+The signals that separate v3.1 from v3.0 (version dropdown, base URL, endpoint
+tables, version badge) all live in the **browser** rendering path. Agents read
+`.md`, `llms.txt`, `llms-full.txt`, and the Context7 ingest, none of which walk
+that path — so every one of those signals used to be dropped, and the only
+concrete request an agent could find was a v3.0 curl example.
+
+There are **two markdown renderers**, and they fail differently:
+
+| Surface | Renderer |
+|---------|----------|
+| MDX pages under `/reference/**` (incl. `reference.md`, tag pages) | `getLLMText` + `mdxToCleanMarkdown` in `lib/source.ts` |
+| OpenAPI operation pages (e.g. `getTools.md`) | `openapiPageToMarkdown` in `app/llms.mdx/[[...slug]]/route.ts` |
+
+A fix in `lib/source.ts` alone does not reach operation pages.
+
+**Composition rule** — the rule most likely to be violated by the next person
+adding a channel:
+
+- **Broad channels** (`SESSION_GUARDRAILS`, `DIRECT_EXECUTION_GUARDRAILS`)
+ compose **both** `REST_VERSION_GUIDANCE` and `TOOL_VERSION_GUIDANCE`. Their
+ reader may call any endpoint.
+- **OpenAPI operation pages** get `REST_VERSION_GUIDANCE` always, and
+ `TOOL_VERSION_GUIDANCE` only when `isToolVersionPath` matches. They do **not**
+ get `SESSION_GUARDRAILS` — it is about SDK code generation, and since it
+ composes the tool-version text it would force it onto operations it does not
+ apply to.
+- **Top notes** (`getLLMText`, `openapiPageToMarkdown`) carry **neither**. They
+ are a pointer only: which version, the base URL, the cross-version link. The
+ guidance already appears further down the same response.
+
+Two more rules:
+
+- **Any new version-dependent rendering must go through `detectApiVersion`**
+ (`lib/api-version.ts`), never an inline `/reference/v3/` string test. Moving
+ the legacy tree's URL should be a one-line change in that file.
+- **Normalization is `isToolVersionPath`'s job, and only its job.** Callers pass
+ the raw spec path key verbatim (`/api/v3.1/tools/{tool_slug}`, with the `/api`
+ segment). It strips `/api/v3.1` before `/api/v3` and compares by exact set
+ membership — `/tools/enum`, `/tools/execute/proxy`, and
+ `tool_router/…/tools` all mention `tools` and none of them is affected.
+
### Content structure
v3.0 has its own complete page tree under `content/reference/v3/`:
diff --git a/docs/app/llms-full.txt/route.ts b/docs/app/llms-full.txt/route.ts
index d42a6adae..e91b8f452 100644
--- a/docs/app/llms-full.txt/route.ts
+++ b/docs/app/llms-full.txt/route.ts
@@ -7,6 +7,7 @@ import {
type LLMPage,
} from '@/lib/source';
import { SESSION_GUARDRAILS } from '@/lib/llm-guardrails';
+import { detectReferenceApiVersion } from '@/lib/api-version';
import type { ReactNode } from 'react';
export const revalidate = false;
@@ -122,7 +123,6 @@ async function getTextForPages(pages: PageLike[]) {
includeGuardrails: false,
});
} catch {
- // Graceful fallback if getText fails
return `# ${page.data.title} (${page.url})\n\n${page.data.description || ''}`;
}
})
@@ -141,7 +141,9 @@ export async function GET() {
const [docsResults, examplesResults, referenceResults, toolkitsResults] = await Promise.all([
getTextForPages(orderedDocsPages),
getTextForPages(examplesSource.getPages()),
- getTextForPages(referenceSource.getPages()),
+ getTextForPages(
+ referenceSource.getPages().filter(page => detectReferenceApiVersion(page.url) !== '3.0')
+ ),
getTextForPages(toolkitsSource.getPages()),
]);
diff --git a/docs/app/llms.mdx/[[...slug]]/route.ts b/docs/app/llms.mdx/[[...slug]]/route.ts
index 3a0b45241..ff483c3b2 100644
--- a/docs/app/llms.mdx/[[...slug]]/route.ts
+++ b/docs/app/llms.mdx/[[...slug]]/route.ts
@@ -11,6 +11,13 @@ import {
type LLMPage,
} from '@/lib/source';
import { dereferenceDocument } from '@/lib/openapi-deref';
+import {
+ REST_VERSION_GUIDANCE,
+ TOOL_VERSION_GUIDANCE,
+ apiVersionPointer,
+ isToolVersionPath,
+ toolVersionParameterDescription,
+} from '@/lib/api-version-guidance';
import { notFound } from 'next/navigation';
import { readFile } from 'fs/promises';
import { join } from 'path';
@@ -372,6 +379,23 @@ function renderSchema(schema: OpenAPISchema, indent = 0, maxDepth = 4, depth = 0
return lines;
}
+/** Overrides only the top-level request-body version field for affected tool operations. */
+function withToolVersionDescription(rawSpecPath: string, schema: OpenAPISchema): OpenAPISchema {
+ const versionProperty = schema.properties?.version;
+ if (!versionProperty || !isToolVersionPath(rawSpecPath)) return schema;
+
+ return {
+ ...schema,
+ properties: {
+ ...schema.properties,
+ version: {
+ ...versionProperty,
+ description: toolVersionParameterDescription(rawSpecPath, versionProperty.description),
+ },
+ },
+ };
+}
+
// Get a readable type string
function getTypeString(schema: OpenAPISchema, depth = 0, maxDepth = 4): string {
if (depth > maxDepth) return '...';
@@ -451,6 +475,15 @@ export async function openapiPageToMarkdown(page: {
const lines: string[] = [`# ${title}`, ''];
lines.push(`**Documentation:** ${page.url}`, '');
+ // Which REST version this page documents, emitted above the `**Endpoint:**`
+ // line below so a truncating reader still sees it. These pages publish a
+ // complete working curl example and never touch mdxToCleanMarkdown, so
+ // without this the strongest v3 signal in the corpus stays unlabelled.
+ const versionPointer = apiVersionPointer(page.url);
+ if (versionPointer) {
+ lines.push(versionPointer.trim(), '');
+ }
+
if (description) {
lines.push(description, '');
}
@@ -548,7 +581,12 @@ export async function openapiPageToMarkdown(page: {
for (const param of queryParams) {
const typeStr = getTypeString(param.schema || { type: 'string' });
const reqMark = param.required ? ' *(required)*' : '';
- lines.push(`- \`${param.name}\` (${typeStr})${reqMark}: ${param.description || ''}`);
+ const description =
+ (param.name === 'version' || param.name === 'toolkit_versions') &&
+ isToolVersionPath(name)
+ ? toolVersionParameterDescription(name, param.description)
+ : param.description || '';
+ lines.push(`- \`${param.name}\` (${typeStr})${reqMark}: ${description}`);
}
lines.push('');
}
@@ -573,8 +611,9 @@ export async function openapiPageToMarkdown(page: {
}
const schema = operation.requestBody.content['application/json'].schema;
if (schema) {
+ const renderedSchema = withToolVersionDescription(name, schema);
lines.push('**Schema:**', '');
- lines.push(...renderSchema(schema));
+ lines.push(...renderSchema(renderedSchema));
lines.push('');
// Example
@@ -623,6 +662,24 @@ export async function openapiPageToMarkdown(page: {
}
}
+ // Guidance goes after the operation body. Operation pages deliberately do
+ // NOT receive SESSION_GUARDRAILS: that block is about SDK code generation,
+ // it would be noise on a REST operation page, and — because it composes
+ // TOOL_VERSION_GUIDANCE — it would force the tool-version text onto every
+ // operation regardless of scope.
+ //
+ // The baseline applies to every operation. The tool-version note applies to
+ // exactly the five endpoints whose version default changes, decided by
+ // isToolVersionPath on the RAW spec path key (`/api/v3.1/tools/{tool_slug}`)
+ // — normalization belongs to the predicate, so nothing is stripped here and
+ // nothing keys off the page URL.
+ if (selectedOperations.length > 0) {
+ lines.push('---', '', REST_VERSION_GUIDANCE);
+ if (selectedOperations.some(selected => isToolVersionPath(selected.name))) {
+ lines.push('', TOOL_VERSION_GUIDANCE);
+ }
+ }
+
return lines.join('\n').trim();
}
diff --git a/docs/app/llms.txt/route.ts b/docs/app/llms.txt/route.ts
index 5c4466965..5b19a0b38 100644
--- a/docs/app/llms.txt/route.ts
+++ b/docs/app/llms.txt/route.ts
@@ -1,4 +1,5 @@
import { source, examplesSource, referenceSource, toolkitsSource } from '@/lib/source';
+import { detectReferenceApiVersion } from '@/lib/api-version';
import type { ReactNode } from 'react';
export const revalidate = false;
@@ -99,13 +100,51 @@ function formatPage(page: { url: string }) {
return `- https://docs.composio.dev${page.url}.md`;
}
+/**
+ * Splits reference pages by REST version.
+ *
+ * This list is built with a flat `.map(formatPage)` that bypasses the
+ * `isLegacySeparator` filter the guides tree gets, so the two trees used to
+ * arrive interleaved under one unlabelled heading — and `/reference/v3/` is
+ * the only version-shaped path in the corpus, so it is the highest-precision
+ * match for the query most readers intend as "current Composio".
+ *
+ * Partitioned with `detectApiVersion`, not a literal path test, so moving the
+ * legacy tree's URL stays a one-line change in `lib/api-version.ts`.
+ */
+function partitionByApiVersion<T extends { url: string }>(pages: T[]) {
+ const current: T[] = [];
+ const legacy: T[] = [];
+ const versionIndependent: T[] = [];
+ for (const page of pages) {
+ const version = detectReferenceApiVersion(page.url);
+ if (version === '3.0') legacy.push(page);
+ else if (version === '3.1') current.push(page);
+ else versionIndependent.push(page);
+ }
+ return { current, legacy, versionIndependent };
+}
+
export async function GET() {
try {
const docsTree = walkPageTree(source.pageTree.children as TreeNode[]);
const examplesPages = examplesSource.getPages();
- const referencePages = referenceSource.getPages();
const toolkitsPages = toolkitsSource.getPages();
+ const {
+ current: currentReferencePages,
+ legacy: legacyReferencePages,
+ versionIndependent: versionIndependentReferencePages,
+ } = partitionByApiVersion(referenceSource.getPages());
+
+ const legacyReferenceSection =
+ legacyReferencePages.length > 0
+ ? `
+## API Reference (v3.0, legacy — supported, not for new code)
+
+${legacyReferencePages.map(formatPage).join('\n')}
+`
+ : '';
const index = `# Composio Documentation
@@ -119,9 +158,13 @@ ${docsTree}
${examplesPages.map(formatPage).join('\n')}
-## API Reference
+## API Reference (v3.1, current)
+
+${currentReferencePages.map(formatPage).join('\n')}
+${legacyReferenceSection}
+## SDK and product reference (version-independent)
-${referencePages.map(formatPage).join('\n')}
+${versionIndependentReferencePages.map(formatPage).join('\n')}
## Toolkits
diff --git a/docs/components/api-base-url.tsx b/docs/components/api-base-url.tsx
index a2037e5b3..42e496a3e 100644
--- a/docs/components/api-base-url.tsx
+++ b/docs/components/api-base-url.tsx
@@ -1,18 +1,17 @@
'use client';
import { useApiVersion } from '@/lib/use-api-version';
-
-const BASE_URLS: Record<string, string> = {
- '3.1': 'https://backend.composio.dev/api/v3.1',
- '3.0': 'https://backend.composio.dev/api/v3',
-};
+import { API_BASE_URLS } from '@/lib/api-version';
/**
* Renders the API base URL for the currently selected version.
* Detects version from URL path (/reference/v3/ = v3.0, otherwise v3.1).
+ *
+ * The `.md` channel renders this tag through `mdxToCleanMarkdown`, which reads
+ * the same `API_BASE_URLS` map — the browser and the agent see one URL.
*/
export function ApiBaseUrl() {
const version = useApiVersion();
- return <code>{BASE_URLS[version] ?? BASE_URLS['3.1']}</code>;
+ return <code>{API_BASE_URLS[version] ?? API_BASE_URLS['3.1']}</code>;
}
diff --git a/docs/components/api-endpoints-table.tsx b/docs/components/api-endpoints-table.tsx
index e459f7c73..6fdd63b21 100644
--- a/docs/components/api-endpoints-table.tsx
+++ b/docs/components/api-endpoints-table.tsx
@@ -3,23 +3,16 @@
import { useApiVersion } from '@/lib/use-api-version';
import { DeprecatedApiLegacyBadge } from '@/components/legacy-badge';
import { getApiDisplayTitle } from '@/lib/api-deprecation';
-
-interface Endpoint {
- method: string;
- pathV31: string;
- pathV3: string;
- summary: string;
- href: string;
- /** Set by the generator for operations flagged `deprecated` in the OpenAPI
- * spec. Surfaced with the existing "Legacy" tag (see components/legacy-badge.tsx). */
- legacy?: boolean;
-}
+import type { ApiEndpoint } from '@/lib/api-endpoints-table-schema';
/**
* Renders an endpoint table that updates based on the selected API version.
* Used in auto-generated index pages.
+ *
+ * The prop shape lives in `lib/api-endpoints-table-schema.ts` — one type, one
+ * source, shared with the `.md` converter and the generator's validation.
*/
-export function ApiEndpointsTable({ endpoints }: { endpoints: Endpoint[] }) {
+export function ApiEndpointsTable({ endpoints }: { endpoints: ApiEndpoint[] }) {
const version = useApiVersion();
return (
diff --git a/docs/lib/api-endpoints-table-schema.ts b/docs/lib/api-endpoints-table-schema.ts
new file mode 100644
index 000000000..d66ce0760
--- /dev/null
+++ b/docs/lib/api-endpoints-table-schema.ts
@@ -0,0 +1,34 @@
+import { z } from 'zod';
+
+/**
+ * The `endpoints={[...]}` prop of `<ApiEndpointsTable />`.
+ *
+ * `scripts/generate-api-index.ts` serializes this array into MDX as a JSON
+ * string, so every reader — the React component, the `.md` converter in
+ * `lib/source.ts`, and the route guard in
+ * `tests/static/api-reference-routes.test.ts` — is reading external data and
+ * parses it here once, with `z.infer` flowing downstream.
+ *
+ * Deliberately non-strict: unknown keys are stripped rather than rejected, so
+ * adding a field to the generator does not break rendering on pages generated
+ * before the field existed.
+ */
+export const apiEndpointSchema = z.object({
+ method: z.string(),
+ /** Path under the current prefix, e.g. `/api/v3.1/tools/{tool_slug}`. */
+ pathV31: z.string(),
+ /** Same operation under the previous prefix, e.g. `/api/v3/tools/{tool_slug}`. */
+ pathV3: z.string(),
+ summary: z.string(),
+ href: z.string(),
+ /**
+ * Set by the generator for operations flagged `deprecated` in the OpenAPI
+ * spec. Surfaced with the existing "Legacy" tag (see
+ * `components/legacy-badge.tsx`).
+ */
+ legacy: z.boolean().optional(),
+});
+
+export const apiEndpointsSchema = z.array(apiEndpointSchema);
+
+export type ApiEndpoint = z.infer<typeof apiEndpointSchema>;
diff --git a/docs/lib/api-version-guidance.ts b/docs/lib/api-version-guidance.ts
new file mode 100644
index 000000000..e77117a72
--- /dev/null
+++ b/docs/lib/api-version-guidance.ts
@@ -0,0 +1,96 @@
+/** Shared version guidance for agent-facing markdown. */
+
+import {
+ API_BASE_URLS,
+ detectApiVersion,
+ isReferenceUrl,
+ toCurrentVersionUrl,
+} from './api-version';
+
+/** Baseline guidance for all REST operations. */
+export const REST_VERSION_GUIDANCE = `## REST API version
+
+The current REST API version is **v3.1**, served at \`${API_BASE_URLS['3.1']}\`. Prefer it for new code and new examples.
+
+\`${API_BASE_URLS['3.0']}\` is the previous version. It is frozen with pinned tool-version defaults and remains supported — existing v3 integrations keep working and do not need to migrate.`;
+
+/** Version-stripped tool paths whose defaults need explicit guidance. */
+export const TOOL_VERSION_PATHS = [
+ '/tools',
+ '/tools/{tool_slug}',
+ '/tools/execute/{tool_slug}',
+ '/tools/execute/{tool_slug}/input',
+ '/tools/scopes/required',
+] as const;
+
+/** Guidance for the tool-endpoint defaults that differ across REST versions. */
+export const TOOL_VERSION_GUIDANCE = `## Tool-endpoint version defaults on v3.1
+
+On v3.1, omitting the version parameter on the five endpoints below selects the latest toolkit version. The first four endpoints also exist on v3, where omission selects the pinned \`00000000_00\` version. \`POST /tools/scopes/required\` is v3.1-only.
+
+| Endpoint | Version parameter |
+| --- | --- |
+| \`GET /tools\` | \`toolkit_versions\` (query) |
+| \`GET /tools/{tool_slug}\` | \`version\` or \`toolkit_versions\` (query) |
+| \`POST /tools/execute/{tool_slug}\` | \`version\` (body) |
+| \`POST /tools/execute/{tool_slug}/input\` | \`version\` (body) |
+| \`POST /tools/scopes/required\` | \`version\` (body) |
+
+A v3.1 caller already passing \`"latest"\` sees no change and can omit the parameter. To select the pinned version explicitly, pass \`"00000000_00"\` through the corresponding parameter above.
+
+This version-default change is limited to the five endpoints above.`;
+
+const TOOL_VERSION_PATH_SET: ReadonlySet<string> = new Set(TOOL_VERSION_PATHS);
+
+/** Longest prefix first to avoid matching `/api/v3` inside `/api/v3.1`. */
+const VERSION_PREFIXES = ['/api/v3.1', '/api/v3'] as const;
+
+/**
+ * Replaces stale OpenAPI default prose with the deployed REST-version default.
+ * The source specs are generated upstream, so the agent-facing renderer fixes
+ * their description without mutating the generated snapshots.
+ */
+export function toolVersionParameterDescription(
+ rawSpecPath: string,
+ description = 'Tool version to use'
+): string {
+ if (!isToolVersionPath(rawSpecPath)) return description;
+
+ const apiVersion = rawSpecPath.startsWith('/api/v3.1') ? '3.1' : '3.0';
+ const defaultVersion = apiVersion === '3.1' ? 'latest' : '00000000_00';
+ const withoutDefault = description.replace(/\s*\(?defaults?\s+to\b[\s\S]*$/i, '').trim();
+ const base = (withoutDefault || 'Tool version to use').replace(/[.:]\s*$/, '');
+
+ return `${base}. Defaults to \`${defaultVersion}\` when omitted on REST API v${apiVersion}.`;
+}
+
+/**
+ * The short version pointer for a reference page: which version this page
+ * documents, its base URL, and — on a legacy page — the link to the same page
+ * on v3.1. Empty outside the reference tree.
+ *
+ * A pointer, not guidance: the guardrail block (MDX pages) or
+ * `REST_VERSION_GUIDANCE` (operation pages) already carries the explanation
+ * further down the same response, and repeating it would put the same
+ * paragraph twice. Both renderers call this so their pointers agree by
+ * construction.
+ */
+export function apiVersionPointer(pageUrl: string): string {
+ if (!isReferenceUrl(pageUrl)) return '';
+
+ if (detectApiVersion(pageUrl) === '3.0') {
+ const currentUrl = `${toCurrentVersionUrl(pageUrl)}.md`;
+ return `\n> **API version:** This page documents Composio REST API v3.0 at \`${API_BASE_URLS['3.0']}\`, the previous version. v3.1 is current, at \`${API_BASE_URLS['3.1']}\` — the same page on v3.1 is ${currentUrl}.\n`;
+ }
+
+ return `\n> **API version:** This page documents Composio REST API v3.1, the current version, at \`${API_BASE_URLS['3.1']}\`. \`${API_BASE_URLS['3.0']}\` is the previous version and remains supported.\n`;
+}
+
+export function isToolVersionPath(rawSpecPath: string): boolean {
+ for (const prefix of VERSION_PREFIXES) {
+ if (rawSpecPath.startsWith(prefix)) {
+ return TOOL_VERSION_PATH_SET.has(rawSpecPath.slice(prefix.length));
+ }
+ }
+ return false;
+}
diff --git a/docs/lib/api-version.ts b/docs/lib/api-version.ts
index 3906fe002..ef0b94258 100644
--- a/docs/lib/api-version.ts
+++ b/docs/lib/api-version.ts
@@ -4,6 +4,19 @@
*/
export type ApiVersion = '3.1' | '3.0';
+export type ReferenceApiVersion = ApiVersion | null;
+
+/**
+ * REST base URL per API version. Single source of truth — the browser
+ * component (`components/api-base-url.tsx`), the markdown converter
+ * (`lib/source.ts`), and the version guidance constants
+ * (`lib/api-version-guidance.ts`) all read it from here rather than
+ * spelling the URL out again.
+ */
+export const API_BASE_URLS: Record<ApiVersion, string> = {
+ '3.1': 'https://backend.composio.dev/api/v3.1',
+ '3.0': 'https://backend.composio.dev/api/v3',
+};
/**
* Detects the API version from a pathname.
@@ -14,3 +27,36 @@ export function detectApiVersion(pathname: string): ApiVersion {
? '3.0'
: '3.1';
}
+
+/** True for reference pages that describe the REST API. */
+export function isReferenceUrl(pathname: string): boolean {
+ return (
+ pathname !== '/reference/glossary' &&
+ pathname !== '/reference/sdk-reference' &&
+ !pathname.startsWith('/reference/sdk-reference/') &&
+ (pathname === '/reference' || pathname.startsWith('/reference/'))
+ );
+}
+
+/** The REST version described by a reference page, or null for SDK/glossary pages. */
+export function detectReferenceApiVersion(pathname: string): ReferenceApiVersion {
+ return isReferenceUrl(pathname) ? detectApiVersion(pathname) : null;
+}
+
+const CURRENT_VERSION_URLS: Record<string, string> = {
+ '/reference/v3/authentication': '/reference/authenticating-to-composio',
+};
+
+/**
+ * The current-version URL for a legacy-tree page, so an agent reading a v3.0
+ * page can be pointed at the same operation on v3.1. Any other pathname is
+ * returned unchanged.
+ */
+export function toCurrentVersionUrl(pathname: string): string {
+ if (CURRENT_VERSION_URLS[pathname]) return CURRENT_VERSION_URLS[pathname];
+ if (pathname === '/reference/v3') return '/reference';
+ if (pathname.startsWith('/reference/v3/')) {
+ return `/reference/${pathname.slice('/reference/v3/'.length)}`;
+ }
+ return pathname;
+}
diff --git a/docs/lib/llm-guardrails/direct-execution.ts b/docs/lib/llm-guardrails/direct-execution.ts
index 7b933cfb8..d46a67fde 100644
--- a/docs/lib/llm-guardrails/direct-execution.ts
+++ b/docs/lib/llm-guardrails/direct-execution.ts
@@ -1,8 +1,12 @@
import { TERMINOLOGY_MIGRATION } from './terminology';
+import { REST_VERSION_GUIDANCE, TOOL_VERSION_GUIDANCE } from '../api-version-guidance';
/**
* Guardrails for pages tagged with llmGuardrails: "direct-execution".
* Concise rules + key patterns for LLMs generating direct execution code.
+ *
+ * Broad channel, so it composes both version guidance constants — interpolated
+ * from `lib/api-version-guidance.ts`, never retyped.
*/
export const DIRECT_EXECUTION_GUARDRAILS = `
@@ -78,5 +82,13 @@ const result = await composio.tools.execute("GITHUB_CREATE_ISSUE", {
4. **Provider at init** — \`Composio(provider=OpenAIProvider())\` in Python, \`new Composio({ provider: new OpenAIProvider() })\` in TypeScript. Defaults to OpenAI if omitted.
5. **Correct provider imports** — \`composio_<provider>\` for Python, \`@composio/<provider>\` for TypeScript. For OpenAI Agents SDK use \`composio_openai_agents\` / \`@composio/openai-agents\`.
6. **Finding toolkit and tool slugs** — browse the Toolkits catalog at https://docs.composio.dev/toolkits (each toolkit page lists tool slugs and versions), or search by task with the CLI: \`composio search "<what you want to do>"\`.
+
+---
+
+# Calling the REST API directly
+
+${REST_VERSION_GUIDANCE}
+
+${TOOL_VERSION_GUIDANCE}
${TERMINOLOGY_MIGRATION}
`;
diff --git a/docs/lib/llm-guardrails/session.ts b/docs/lib/llm-guardrails/session.ts
index da9aa5feb..5f1ae5be7 100644
--- a/docs/lib/llm-guardrails/session.ts
+++ b/docs/lib/llm-guardrails/session.ts
@@ -1,4 +1,5 @@
import { TERMINOLOGY_MIGRATION } from './terminology';
+import { REST_VERSION_GUIDANCE, TOOL_VERSION_GUIDANCE } from '../api-version-guidance';
/**
* Default integration notes appended to most pages.
@@ -8,6 +9,11 @@ import { TERMINOLOGY_MIGRATION } from './terminology';
* (Rewritten after two eval rounds showed capable agents classify
* ALWAYS/NEVER-style instruction blocks as prompt injection and distrust the
* page they appear on.)
+ *
+ * A reader of a session guide may call any endpoint, so this is a broad
+ * channel: it composes both version guidance constants. They are interpolated
+ * from `lib/api-version-guidance.ts`, never retyped — see the composition rule
+ * there.
*/
export const SESSION_GUARDRAILS = `
@@ -60,5 +66,13 @@ Use \`session.mcp.url\` and \`session.mcp.headers\` with any MCP-compatible clie
- Composio-managed auth is the default: the agent connects accounts at runtime through the session, so users don't need to pre-create auth configs or connected accounts for managed toolkits.
- Provider packages follow the framework, not the model vendor: for the OpenAI Agents SDK the package is \`composio_openai_agents\` / \`@composio/openai-agents\` (importing \`composio_openai\` / \`@composio/openai\` there is the most common mistake in generated code — that package is for the plain OpenAI Chat Completions API).
- **Direct execution** (\`composio.tools.get()\`, \`composio.tools.execute()\`, \`provider.handle_tool_calls()\`) is a fully supported lower-level interface: your code picks the tool, no runtime discovery. It fits deterministic workflows and scripts; sessions fit agents that decide at runtime. The tradeoffs are documented at https://docs.composio.dev/docs/sessions-vs-direct-execution. Note that direct execution requires a toolkit version (https://docs.composio.dev/docs/tools-direct/toolkit-versioning).
+
+---
+
+# 3. Calling the REST API directly
+
+${REST_VERSION_GUIDANCE}
+
+${TOOL_VERSION_GUIDANCE}
${TERMINOLOGY_MIGRATION}
`;
diff --git a/docs/lib/search-index.ts b/docs/lib/search-index.ts
index 8a7026bf4..77e7b18f4 100644
--- a/docs/lib/search-index.ts
+++ b/docs/lib/search-index.ts
@@ -332,7 +332,7 @@ function recordsFromMarkdownPage(input: {
const isLegacy = input.legacy === true;
const resolvedPageRank = isLegacy ? LEGACY_PAGE_RANK : pageRank(input.url, input.type);
const resolvedTags = isLegacy ? [...(input.tags ?? []), 'legacy'] : input.tags;
- const clean = mdxToCleanMarkdown(input.markdown);
+ const clean = mdxToCleanMarkdown(input.markdown, input.url);
const lines = clean.split('\n');
const headingSlugs = new Map<string, number>();
const headings: string[] = [];
diff --git a/docs/lib/source.ts b/docs/lib/source.ts
index 83e5e93ee..21dfeee9a 100644
--- a/docs/lib/source.ts
+++ b/docs/lib/source.ts
@@ -8,6 +8,9 @@ import { HIDDEN_API_TAGS } from './filter-api-version';
import { FILE_BUILDS } from './file-builds';
import { replaceRepoBrowserMarkdown } from './repo-browser-markdown';
import { transformDeprecatedApiSidebarNode } from './deprecated-api-sidebar';
+import { API_BASE_URLS, detectApiVersion, type ApiVersion } from './api-version';
+import { apiVersionPointer } from './api-version-guidance';
+import { apiEndpointsSchema } from './api-endpoints-table-schema';
/**
* True if a reference URL belongs to an intentionally-hidden API tag
@@ -149,16 +152,115 @@ export function getOgImageUrl(
return `https://og.composio.dev/api/og?title=${encodedTitle}`;
}
+/**
+ * `<ApiEndpointsTable />` reaches this converter in two different shapes.
+ *
+ * `getLLMText` reads fumadocs' *processed* markdown, which re-serializes the
+ * JSX expression attribute as a quoted string with the inner quotes escaped:
+ *
+ * <ApiEndpointsTable endpoints="[{&#x22;method&#x22;:&#x22;GET&#x22;, ...}]" />
+ *
+ * while `lib/search-index.ts` passes the raw file content, which keeps the
+ * authored form:
+ *
+ * <ApiEndpointsTable endpoints={[{"method":"GET", ...}]} />
+ *
+ * Matching only the authored form is what left the Endpoints section empty on
+ * every live tag page, so both are matched here. Braces are not escaped in the
+ * processed form, and every inner `"` is — so a non-greedy match to the next
+ * unescaped quote is exact.
+ */
+const API_ENDPOINTS_TABLE_REGEX =
+ /<ApiEndpointsTable\s+endpoints=(?:\{([\s\S]*?)\}\s*\/>|"([\s\S]*?)"\s*\/>)/g;
+
+/** Reverses the entity escaping fumadocs applies to JSX attribute values. */
+function decodeHtmlEntities(value: string): string {
+ return value
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, hex: string) =>
+ String.fromCodePoint(Number.parseInt(hex, 16))
+ )
+ .replace(/&#(\d+);/g, (_, dec: string) => String.fromCodePoint(Number.parseInt(dec, 10)))
+ .replace(/&quot;/g, '"')
+ .replace(/&apos;/g, "'")
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&amp;/g, '&');
+}
+
+/**
+ * Renders an `<ApiEndpointsTable />` payload as a markdown table.
+ *
+ * Degrades rather than throws: a malformed payload emits nothing for that one
+ * table and warns, because taking the whole `.md` response down over one bad
+ * page is worse. The failure signal for checked-in content lives in the static
+ * suite instead — `tests/static/api-reference-routes.test.ts` runs every
+ * committed payload through the same schema, and
+ * `scripts/generate-api-index.ts` refuses to write an invalid one.
+ */
+function endpointsTableToMarkdown(payload: string, version: ApiVersion, url?: string): string {
+ const where = url ?? '(no page url)';
+
+ let json: unknown;
+ try {
+ json = JSON.parse(payload);
+ } catch {
+ console.warn(`[mdxToCleanMarkdown] unparseable ApiEndpointsTable payload on ${where}`);
+ return '';
+ }
+
+ const parsed = apiEndpointsSchema.safeParse(json);
+ if (!parsed.success) {
+ console.warn(`[mdxToCleanMarkdown] invalid ApiEndpointsTable payload on ${where}`);
+ return '';
+ }
+
+ const rows = parsed.data.map(endpoint => {
+ const path = version === '3.0' ? endpoint.pathV3 : endpoint.pathV31;
+ const summary = endpoint.summary
+ .replace(/\\/g, '\\\\')
+ .replace(/\|/g, '\\|')
+ .replace(/\n/g, ' ');
+ const label = endpoint.legacy ? `${summary} (Legacy)` : summary;
+ return `| \`${endpoint.method}\` | \`${path}\` | [${label}](${endpoint.href}) |`;
+ });
+
+ return ['| Method | Path | Endpoint |', '| --- | --- | --- |', ...rows].join('\n');
+}
+
/**
* Converts MDX content to clean markdown for AI agents.
* Strips JSX components and converts them to plain text equivalents.
+ *
+ * `url` is the page URL. `ApiBaseUrl` and `ApiEndpointsTable` are client
+ * components that pick a version from `usePathname()`, which the `.md` channel
+ * has no access to — so the URL is passed in and resolved with the same
+ * `detectApiVersion`. Optional because the changelog call sites have no page
+ * URL; with none, the page is treated as current (v3.1), which is correct
+ * there since the changelog tree is not versioned.
*/
-export function mdxToCleanMarkdown(content: string): string {
+export function mdxToCleanMarkdown(content: string, url?: string): string {
let result = content;
+ const version = url ? detectApiVersion(url) : '3.1';
// Remove frontmatter
result = result.replace(/^---[\s\S]*?---\n*/m, '');
+ // Version-dependent API components. These must run before the generic JSX
+ // strippers at the bottom of this function, which would otherwise drop both
+ // tags — publishing an empty `Base URL` bullet and an empty `Endpoints`
+ // section to every agent while the superseded v3.0 operation pages published
+ // a complete working request. That asymmetry is why agents reached for v3.
+ result = result.replace(/<ApiBaseUrl\s*\/>/g, `\`${API_BASE_URLS[version]}\``);
+ result = result.replace(
+ API_ENDPOINTS_TABLE_REGEX,
+ (_, bracedPayload?: string, quotedPayload?: string) =>
+ endpointsTableToMarkdown(
+ bracedPayload ?? decodeHtmlEntities(quotedPayload ?? ''),
+ version,
+ url
+ )
+ );
+
// Convert YouTube to link
result = result.replace(
/<YouTube\s+id="([^"]+)"\s+title="([^"]+)"\s*\/>/g,
@@ -459,7 +561,7 @@ ${page.data.description || ''}`;
}
segments.push(content.slice(lastIndex));
- const cleanSegments = segments.map(s => mdxToCleanMarkdown(s));
+ const cleanSegments = segments.map(s => mdxToCleanMarkdown(s, page.url));
let cleanContent = cleanSegments[0];
for (let i = 0; i < mermaidCharts.length; i++) {
const chart = mermaidCharts[i]
@@ -479,12 +581,17 @@ ${page.data.description || ''}`;
// legacy guide contradicts the guide's own (older) content.
const isLegacy = page.data.legacy === true;
const written = page.data.written;
- const topNote = isLegacy
+ const frontmatterNote = isLegacy
? `\n> **Legacy${written ? ` · written ${written}` : ''}.** This is a point-in-time migration/legacy guide and may describe outdated APIs. For current guidance, see https://docs.composio.dev.\n`
: written
? `\n> _Written ${written}._\n`
: '';
+ // Which REST version this page documents. Scoped to the reference tree —
+ // /docs/** has no REST version — and carries no guidance paragraph, because
+ // the guardrail block further down this same response already does.
+ const topNote = `${frontmatterNote}${apiVersionPointer(page.url)}`;
+
const guardrails = includeGuardrails && !isLegacy ? getGuardrails(page.data.llmGuardrails) : '';
return `# ${page.data.title} (${page.url})
diff --git a/docs/scripts/generate-api-index.ts b/docs/scripts/generate-api-index.ts
index 42d45bea1..dda77fcaa 100644
--- a/docs/scripts/generate-api-index.ts
+++ b/docs/scripts/generate-api-index.ts
@@ -8,7 +8,29 @@
import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, readdirSync } from 'fs';
import { join } from 'path';
+import { z } from 'zod';
import { HIDDEN_API_TAGS } from '../lib/filter-api-version';
+import { apiEndpointsSchema } from '../lib/api-endpoints-table-schema';
+
+/**
+ * Serializes an endpoints array for the `<ApiEndpointsTable />` prop, refusing
+ * to write a payload the readers cannot parse.
+ *
+ * At runtime `mdxToCleanMarkdown` degrades a malformed payload to an empty
+ * table (one bad page must not 500 the whole `.md` response), so an invalid
+ * payload written here would render as a silently empty Endpoints section —
+ * exactly the defect this pipeline exists to avoid. A generator that cannot
+ * produce a valid payload should fail the generation run instead.
+ */
+function serializeEndpoints(endpoints: unknown, label: string): string {
+ const parsed = apiEndpointsSchema.safeParse(endpoints);
+ if (!parsed.success) {
+ throw new Error(
+ `Invalid ApiEndpointsTable payload for ${label}:\n${z.prettifyError(parsed.error)}`
+ );
+ }
+ return JSON.stringify(endpoints);
+}
/**
* API-reference tags hidden on our side even though the upstream OpenAPI spec
@@ -263,16 +285,14 @@ function generateIndexPages() {
let v3Ops: Record<string, OperationEntry[]> = {};
if (existsSync(specV3Path)) {
- const specV3: OpenAPISpec = JSON.parse(readFileSync(specV3Path, 'utf-8'));
- v3Ops = getOperationsByTag(specV3);
+ const loadedSpecV3: OpenAPISpec = JSON.parse(readFileSync(specV3Path, 'utf-8'));
+ v3Ops = getOperationsByTag(loadedSpecV3);
}
- // Collect tag descriptions from v3.1 spec
- const tagDescriptions: Record<string, string> = {};
+ const v31TagDescriptions: Record<string, string> = {};
for (const tag of specV31.tags) {
- tagDescriptions[tag.name] = tag.description || '';
+ v31TagDescriptions[tag.name] = tag.description || '';
}
-
const outputDir = join(process.cwd(), 'content/reference/api-reference');
const webhookSpec = loadWebhookSpec();
@@ -332,7 +352,7 @@ function generateIndexPages() {
continue;
}
- const tagDescription = tagDescriptions[tagName] || `${tagName} API endpoints`;
+ const tagDescription = v31TagDescriptions[tagName] || `${tagName} API endpoints`;
// Display-title overrides for tags whose OpenAPI name is stale (e.g. the
// tool router is now Sessions). Keyed by slug.
const displayTitle = TITLE_OVERRIDES[tagSlug] ?? tagName;
@@ -377,7 +397,7 @@ ${body}
## Endpoints
-<ApiEndpointsTable endpoints={${JSON.stringify(endpoints)}} />
+<ApiEndpointsTable endpoints={${serializeEndpoints(endpoints, `${tagSlug} (v3.1)`)}} />
`;
const folderPath = join(outputDir, tagSlug);
@@ -411,7 +431,7 @@ ${body}
## Endpoints
-<ApiEndpointsTable endpoints={${JSON.stringify(v3Endpoints)}} />
+<ApiEndpointsTable endpoints={${serializeEndpoints(v3Endpoints, `${tagSlug} (v3.0)`)}} />
`;
const v3FolderPath = join(process.cwd(), 'content/reference/v3/api-reference', tagSlug);
diff --git a/docs/tests/integration/llm-endpoints.test.ts b/docs/tests/integration/llm-endpoints.test.ts
index 907a825b7..7cb849b7a 100644
--- a/docs/tests/integration/llm-endpoints.test.ts
+++ b/docs/tests/integration/llm-endpoints.test.ts
@@ -19,6 +19,58 @@ describe("LLM endpoints - llms.txt", () => {
});
});
+/**
+ * Version labelling of the machine-readable indexes.
+ *
+ * `/reference/v3/` is the only version-shaped path in the corpus, so a search
+ * for "composio api v3" matches the superseded tree exactly. Both index files
+ * used to list the two trees interleaved under one unlabelled `## API
+ * Reference` heading with no v3.1 string anywhere.
+ */
+describe("LLM endpoints - API reference version labelling", () => {
+ const CURRENT_HEADING = "## API Reference (v3.1, current)";
+ const LEGACY_HEADING_PREFIX = "## API Reference (v3.0, legacy";
+
+ test("/llms.txt labels the current reference group", async () => {
+ const text = await (await fetchPage("/llms.txt")).text();
+ expect(text).toContain(CURRENT_HEADING);
+ });
+
+ test("/llms.txt has no unlabelled API Reference heading", async () => {
+ const text = await (await fetchPage("/llms.txt")).text();
+ expect(text.split("\n")).not.toContain("## API Reference");
+ });
+
+ test("/llms.txt groups every legacy URL under the legacy heading, not interleaved", async () => {
+ const lines = (await (await fetchPage("/llms.txt")).text()).split("\n");
+
+ const legacyStart = lines.findIndex(line => line.startsWith(LEGACY_HEADING_PREFIX));
+ expect(legacyStart, "no legacy reference group").toBeGreaterThan(-1);
+
+ // The legacy group runs to the next ## heading.
+ let legacyEnd = lines.findIndex(
+ (line, i) => i > legacyStart && line.startsWith("## "),
+ );
+ if (legacyEnd === -1) legacyEnd = lines.length;
+
+ const strays = lines
+ .map((line, i) => ({ line, i }))
+ .filter(
+ ({ line, i }) =>
+ line.includes("/reference/v3/") && (i < legacyStart || i >= legacyEnd),
+ )
+ .map(({ line }) => line);
+
+ expect(strays, `legacy URLs outside the legacy group:\n${strays.join("\n")}`).toEqual([]);
+ });
+
+ test("/llms-full.txt carries no v3.0 page bodies", async () => {
+ const text = await (await fetchPage("/llms-full.txt")).text();
+ expect(text).not.toContain("/reference/v3/");
+ expect(text).toContain("# Tools (/reference/api-reference/tools)");
+ });
+});
+
describe("LLM endpoints - .md pages", () => {
const MD_PAGES = [
{ path: "/docs/quickstart.md", name: "Quickstart" },
diff --git a/docs/tests/static/api-deprecation.test.tsx b/docs/tests/static/api-deprecation.test.tsx
index 1557b6018..c5a51abb0 100644
--- a/docs/tests/static/api-deprecation.test.tsx
+++ b/docs/tests/static/api-deprecation.test.tsx
@@ -29,7 +29,12 @@ interface SerializedEndpoint {
function createSpec(version: "v3.1" | "v3") {
return {
- tags: [{ name: "Tasks", description: "Task endpoints" }],
+ tags: [
+ {
+ name: "Tasks",
+ description: version === "v3.1" ? "Current task endpoints" : "Legacy task endpoints",
+ },
+ ],
paths: {
[`/${version}/tasks/deprecated`]: {
get: {
@@ -114,6 +119,11 @@ async function generateFixture(options?: { webhookSpec?: ReturnType<typeof creat
join(fixtureDir, "public/openapi-v3.json"),
JSON.stringify(createSpec("v3")),
);
+ await mkdir(join(fixtureDir, "api-overviews"), { recursive: true });
+ await writeFile(
+ join(fixtureDir, "api-overviews/tasks.mdx"),
+ "Current task overview with POST /api/v3.1/tasks/active",
+ );
if (options?.webhookSpec) {
await writeFile(
join(fixtureDir, "public/openapi-webhooks.json"),
@@ -353,6 +363,21 @@ describe("deprecated API endpoints", () => {
}
});
+ test("preserves the shared overview on current and legacy indexes", async () => {
+ const fixtureDir = await generateFixture();
+ const v31Content = await readFile(
+ join(fixtureDir, "content/reference/api-reference/tasks/index.mdx"),
+ "utf-8",
+ );
+ const v3Content = await readFile(
+ join(fixtureDir, "content/reference/v3/api-reference/tasks/index.mdx"),
+ "utf-8",
+ );
+
+ expect(v31Content).toContain("Current task overview with POST /api/v3.1/tasks/active");
+ expect(v3Content).toContain("Current task overview with POST /api/v3.1/tasks/active");
+ });
+
test("renders one Legacy badge for a deprecated endpoint and none for an active endpoint", () => {
const html = renderToStaticMarkup(
<ApiEndpointsTable
diff --git a/docs/tests/static/api-reference-routes.test.ts b/docs/tests/static/api-reference-routes.test.ts
index 4a94e0e9e..6f04c698f 100644
--- a/docs/tests/static/api-reference-routes.test.ts
+++ b/docs/tests/static/api-reference-routes.test.ts
@@ -23,8 +23,10 @@ import { readFileSync, readdirSync } from 'node:fs';
import { join, relative } from 'node:path';
import { loader, multiple } from 'fumadocs-core/source';
import { createOpenAPI, openapiSource } from 'fumadocs-openapi/server';
+import { z } from 'zod';
import { openapi, openapiV3 } from '../../lib/openapi';
+import { apiEndpointsSchema } from '../../lib/api-endpoints-table-schema';
import { HIDDEN_API_TAGS } from '../../lib/filter-api-version';
const DOCS_DIR = join(import.meta.dir, '../..');
@@ -235,7 +237,15 @@ describe('API reference quick links', () => {
return files;
}
- /** Parses the serialized endpoints of every ApiEndpointsTable in a file. */
+ /**
+ * Parses the serialized endpoints of every ApiEndpointsTable in a file.
+ *
+ * Validated through the same schema the runtime uses, not a bare
+ * JSON.parse: `mdxToCleanMarkdown` degrades a malformed payload to an empty
+ * table so one bad page cannot 500 the whole .md response, which means a
+ * structurally broken committed payload would otherwise render nothing with
+ * no failure signal anywhere. This is that signal.
+ */
function parseEndpointHrefs(content: string, file: string): string[] {
const hrefs: string[] = [];
const prefix = /<ApiEndpointsTable endpoints=\{/g;
@@ -244,8 +254,15 @@ describe('API reference quick links', () => {
const start = match.index + match[0].length;
const end = content.indexOf('} />', start);
expect(end, `${file}: unterminated ApiEndpointsTable`).toBeGreaterThan(start);
- const endpoints: { href: string }[] = JSON.parse(content.slice(start, end));
- hrefs.push(...endpoints.map((endpoint) => endpoint.href));
+ const parsed = apiEndpointsSchema.safeParse(JSON.parse(content.slice(start, end)));
+ expect(
+ parsed.success,
+ `${file}: ApiEndpointsTable payload fails apiEndpointsSchema:\n${
+ parsed.success ? '' : z.prettifyError(parsed.error)
+ }`,
+ ).toBe(true);
+ if (!parsed.success) continue;
+ hrefs.push(...parsed.data.map((endpoint) => endpoint.href));
}
// A file mentioning the component but yielding no parsed table means the
// generator's serialization drifted from this extractor — fail loudly
diff --git a/docs/tests/static/api-version-markdown.test.ts b/docs/tests/static/api-version-markdown.test.ts
new file mode 100644
index 000000000..5a1368086
--- /dev/null
+++ b/docs/tests/static/api-version-markdown.test.ts
@@ -0,0 +1,336 @@
+/**
+ * API version identity in the markdown channels.
+ *
+ * Agents read `.md`, not the browser rendering path. Every signal that
+ * separates v3.1 from v3.0 used to live in client components the markdown
+ * converter dropped, so `reference.md` published an empty `Base URL` bullet
+ * and the tag pages published an empty `Endpoints` section — while the
+ * superseded v3.0 operation pages published a complete working curl example.
+ *
+ * These tests lock the three properties that fix costs the most to lose:
+ * 1. `mdxToCleanMarkdown` renders `ApiBaseUrl` and `ApiEndpointsTable` at the
+ * version the page URL implies, and degrades (no table, no throw) on a
+ * malformed payload rather than 500ing the whole `.md` response.
+ * 2. `getLLMText` emits a version pointer on `/reference/**` and nowhere else.
+ * 3. The guidance text is single-sourced in `lib/api-version-guidance.ts` —
+ * asserted by containment of the exported constant, not by matching a
+ * copied literal, which is what proves the guardrail files compose rather
+ * than restate.
+ */
+import { describe, expect, test } from 'bun:test';
+
+import {
+ REST_VERSION_GUIDANCE,
+ TOOL_VERSION_GUIDANCE,
+ TOOL_VERSION_PATHS,
+ apiVersionPointer,
+ isToolVersionPath,
+} from '../../lib/api-version-guidance';
+import { detectReferenceApiVersion, toCurrentVersionUrl } from '../../lib/api-version';
+import {
+ getLLMText,
+ getReferenceSource,
+ mdxToCleanMarkdown,
+ type LLMPage,
+} from '../../lib/source';
+import { DIRECT_EXECUTION_GUARDRAILS, SESSION_GUARDRAILS } from '../../lib/llm-guardrails';
+
+const V31_BASE = 'https://backend.composio.dev/api/v3.1';
+const V30_BASE = 'https://backend.composio.dev/api/v3';
+
+/** A current-tree tag page and its legacy twin. */
+const CURRENT_URL = '/reference/api-reference/tools';
+const LEGACY_URL = '/reference/v3/api-reference/tools';
+
+/** The authored MDX shape, which `lib/search-index.ts` reads from the file. */
+function endpointsTable(endpoints: unknown[]): string {
+ return `## Endpoints\n\n<ApiEndpointsTable endpoints={${JSON.stringify(endpoints)}} />\n`;
+}
+
+/**
+ * The shape `getLLMText` actually receives: fumadocs' processed markdown
+ * re-serializes the JSX expression attribute as a quoted string with the inner
+ * quotes entity-escaped. Matching only the authored shape above still passes a
+ * unit test while leaving every live tag page's Endpoints section empty, which
+ * is exactly the defect this work exists to fix — so the production shape gets
+ * its own fixture.
+ */
+function processedEndpointsTable(endpoints: unknown[]): string {
+ const escaped = JSON.stringify(endpoints).replace(/"/g, '&#x22;');
+ return `## Endpoints\n\n<ApiEndpointsTable endpoints="${escaped}" />\n`;
+}
+
+const TOOLS_ENDPOINT = {
+ method: 'GET',
+ pathV31: '/api/v3.1/tools',
+ pathV3: '/api/v3/tools',
+ summary: 'List tools',
+ href: '/reference/api-reference/tools/getTools',
+};
+
+function llmPage(url: string, content: string, data: Partial<LLMPage['data']> = {}): LLMPage {
+ return {
+ url,
+ data: { title: 'Tools', getText: async () => content, ...data },
+ };
+}
+
+describe('mdxToCleanMarkdown — ApiBaseUrl', () => {
+ test('renders the v3.1 base URL on a current-tree URL', () => {
+ expect(mdxToCleanMarkdown('**Base URL**: <ApiBaseUrl />', CURRENT_URL)).toContain(V31_BASE);
+ });
+
+ test('renders the v3 base URL on a legacy-tree URL', () => {
+ const markdown = mdxToCleanMarkdown('**Base URL**: <ApiBaseUrl />', LEGACY_URL);
+ expect(markdown).toContain(`\`${V30_BASE}\``);
+ expect(markdown).not.toContain(V31_BASE);
+ });
+
+ test('renders the v3.1 base URL with no url argument — the changelog call site', () => {
+ expect(mdxToCleanMarkdown('**Base URL**: <ApiBaseUrl />')).toContain(V31_BASE);
+ });
+});
+
+describe('mdxToCleanMarkdown — ApiEndpointsTable', () => {
+ test('emits one row per endpoint using pathV31 on a current-tree URL', () => {
+ const markdown = mdxToCleanMarkdown(
+ endpointsTable([
+ TOOLS_ENDPOINT,
+ {
+ method: 'POST',
+ pathV31: '/api/v3.1/tools/execute/{tool_slug}',
+ pathV3: '/api/v3/tools/execute/{tool_slug}',
+ summary: 'Execute a tool',
+ href: '/reference/api-reference/tools/executeTool',
+ },
+ ]),
+ CURRENT_URL
+ );
+
+ expect(markdown).toContain('/api/v3.1/tools');
+ expect(markdown).toContain('/api/v3.1/tools/execute/{tool_slug}');
+ expect(markdown).not.toContain('/api/v3/tools');
+ // href kept as a relative link, summary preserved
+ expect(markdown).toContain('[List tools](/reference/api-reference/tools/getTools)');
+ expect(markdown).toContain('[Execute a tool](/reference/api-reference/tools/executeTool)');
+ });
+
+ test('renders the processed-markdown shape getLLMText actually receives', () => {
+ const markdown = mdxToCleanMarkdown(
+ processedEndpointsTable([
+ TOOLS_ENDPOINT,
+ {
+ method: 'GET',
+ pathV31: '/api/v3.1/tools/{tool_slug}',
+ pathV3: '/api/v3/tools/{tool_slug}',
+ summary: 'Get tool by slug',
+ href: '/reference/api-reference/tools/getToolsByToolSlug',
+ },
+ ]),
+ CURRENT_URL
+ );
+
+ expect(markdown).toContain('[List tools](/reference/api-reference/tools/getTools)');
+ expect(markdown).toContain('`/api/v3.1/tools/{tool_slug}`');
+ // The escaping must actually be reversed, not carried through.
+ expect(markdown).not.toContain('&#x22;');
+ });
+
+ test('uses pathV3 on a legacy-tree URL', () => {
+ const markdown = mdxToCleanMarkdown(endpointsTable([TOOLS_ENDPOINT]), LEGACY_URL);
+ expect(markdown).toContain('`/api/v3/tools`');
+ expect(markdown).not.toContain('/api/v3.1/tools');
+ });
+
+ test('renders a visible legacy marker for a deprecated endpoint', () => {
+ const markdown = mdxToCleanMarkdown(
+ endpointsTable([{ ...TOOLS_ENDPOINT, legacy: true }]),
+ CURRENT_URL
+ );
+ expect(markdown).toContain('Legacy');
+ });
+
+ test('preserves backslashes and pipes in endpoint summaries', () => {
+ const markdown = mdxToCleanMarkdown(
+ endpointsTable([{ ...TOOLS_ENDPOINT, summary: String.raw`Path \| pipe` }]),
+ CURRENT_URL
+ );
+
+ expect(markdown).toContain(String.raw`[Path \\\| pipe]`);
+ });
+
+ test('emits no table and does not throw on a truncated payload', () => {
+ const content = 'Surrounding prose.\n\n<ApiEndpointsTable endpoints={[{"method":"GET"} />\n';
+ const markdown = mdxToCleanMarkdown(content, CURRENT_URL);
+ // The rest of the page survives — one bad table must not take the whole
+ // .md response down.
+ expect(markdown).toContain('Surrounding prose.');
+ expect(markdown).not.toContain('| Method |');
+ });
+
+ test('emits no table on a structurally invalid payload a bare JSON.parse would accept', () => {
+ // Valid JSON, pathV31 missing.
+ const markdown = mdxToCleanMarkdown(
+ `Surrounding prose.\n\n${endpointsTable([
+ { method: 'GET', pathV3: '/api/v3/tools', summary: 'List tools', href: '/x' },
+ ])}`,
+ CURRENT_URL
+ );
+ expect(markdown).toContain('Surrounding prose.');
+ expect(markdown).not.toContain('| Method |');
+ expect(markdown).not.toContain('List tools');
+ });
+});
+
+describe('getLLMText — version pointer', () => {
+ test('a current /reference/** page carries the v3.1 pointer and base URL', async () => {
+ const text = await getLLMText(llmPage(CURRENT_URL, '# Tools'), { includeGuardrails: false });
+ expect(text).toContain('**API version:**');
+ expect(text).toContain(V31_BASE);
+ });
+
+ test('a legacy /reference/v3/** page carries the v3.0 pointer and links its v3.1 page', async () => {
+ const text = await getLLMText(llmPage(LEGACY_URL, '# Tools'), { includeGuardrails: false });
+ expect(text).toContain('**API version:**');
+ expect(text).toContain('v3.0');
+ expect(text).toContain(V31_BASE);
+ expect(text).toContain('/reference/api-reference/tools.md');
+ expect(text).not.toContain('https://docs.composio.dev/reference/api-reference/tools.md');
+ });
+
+ test('a /docs/** page gets no API version pointer — the pointer is reference-scoped', async () => {
+ const text = await getLLMText(llmPage('/docs/quickstart', '# Quickstart'));
+ expect(text).not.toContain('**API version:**');
+ });
+
+ test('an SDK reference page gets no REST version pointer', async () => {
+ const text = await getLLMText(
+ llmPage('/reference/sdk-reference/typescript/tools', '# Tools')
+ );
+ expect(text).not.toContain('**API version:**');
+ });
+
+ test('the glossary gets no REST version pointer', async () => {
+ const text = await getLLMText(llmPage('/reference/glossary', '# Glossary'));
+ expect(text).not.toContain('**API version:**');
+ });
+
+ test('the legacy authentication page links to its renamed current counterpart', async () => {
+ const text = await getLLMText(
+ llmPage('/reference/v3/authentication', '# Authentication'),
+ { includeGuardrails: false }
+ );
+ expect(text).toContain('/reference/authenticating-to-composio.md');
+ });
+
+ test('every published legacy page links to an existing current-version page', async () => {
+ const reference = await getReferenceSource();
+ const routes = new Set(reference.getPages().map(page => page.url));
+ const legacyRoutes = [...routes].filter(
+ url => detectReferenceApiVersion(url) === '3.0'
+ );
+ const invalidPointers = legacyRoutes.flatMap(source => {
+ const target = toCurrentVersionUrl(source);
+ const pointer = apiVersionPointer(source);
+ return routes.has(target) &&
+ detectReferenceApiVersion(target) === '3.1' &&
+ pointer.includes(`${target}.md`)
+ ? []
+ : [`${source} -> ${target}`];
+ });
+
+ expect(legacyRoutes.some(url => /^\/reference\/v3\/[^/]+$/.test(url))).toBe(true);
+ expect(
+ legacyRoutes.some(url => /^\/reference\/v3\/api-reference\/[^/]+$/.test(url))
+ ).toBe(true);
+ expect(
+ legacyRoutes.some(url => /^\/reference\/v3\/api-reference\/[^/]+\/[^/]+$/.test(url))
+ ).toBe(true);
+ expect(
+ invalidPointers,
+ `invalid current-version pointers:\n${invalidPointers.join('\n')}`
+ ).toEqual([]);
+ });
+
+ test('a legacy: true page keeps its legacy note and still emits no guardrails', async () => {
+ const text = await getLLMText(
+ llmPage('/docs/tools-direct/executing-tools', '# Executing tools', { legacy: true })
+ );
+ expect(text).toContain('**Legacy');
+ // legacy: true gates the whole guardrail block at source.ts, before the
+ // llmGuardrails selector ever runs. Deliberate: appending "enforce the
+ // CURRENT patterns" to a point-in-time migration guide contradicts it.
+ expect(text).not.toContain('Instructions for AI Code Generators');
+ });
+});
+
+describe('detectReferenceApiVersion', () => {
+ test.each([
+ ['/reference/api-reference/tools', '3.1'],
+ ['/reference/v3/api-reference/tools', '3.0'],
+ ['/reference/glossary', null],
+ ['/reference/sdk-reference', null],
+ ['/reference/sdk-reference/typescript/tools', null],
+ ] as const)('%s is classified as %s', (url, expected) => {
+ expect(detectReferenceApiVersion(url)).toBe(expected);
+ });
+});
+
+describe('guardrail sets compose the guidance rather than restating it', () => {
+ // Containment of the exported constant, not a substring of prose. A test
+ // matching a copied literal would pass just as happily against two strings
+ // that currently agree and are free to drift.
+ test.each([
+ ['SESSION_GUARDRAILS', SESSION_GUARDRAILS],
+ ['DIRECT_EXECUTION_GUARDRAILS', DIRECT_EXECUTION_GUARDRAILS],
+ ])('%s contains both guidance constants verbatim', (_name, guardrails) => {
+ expect(guardrails).toContain(REST_VERSION_GUIDANCE);
+ expect(guardrails).toContain(TOOL_VERSION_GUIDANCE);
+ });
+});
+
+describe('API version guidance constants', () => {
+ test('the REST baseline names v3.1 without claiming route parity', () => {
+ expect(REST_VERSION_GUIDANCE).toContain('https://backend.composio.dev/api/v3.1');
+ expect(TOOL_VERSION_GUIDANCE).toContain(
+ 'This version-default change is limited to the five endpoints above.'
+ );
+ expect(TOOL_VERSION_GUIDANCE).not.toMatch(/every non-tool endpoint.*unchanged/i);
+ });
+
+ test('exactly five tool paths need explicit version-default guidance', () => {
+ expect(TOOL_VERSION_PATHS).toHaveLength(5);
+ });
+});
+
+describe('isToolVersionPath normalization contract', () => {
+ // Every key below appears verbatim in a committed spec. The predicate takes
+ // the raw spec path key; no caller pre-strips anything.
+ const cases: Array<[path: string, expected: boolean, why: string]> = [
+ ['/api/v3.1/tools', true, ''],
+ ['/api/v3.1/tools/{tool_slug}', true, 'fails if /api/v3 is stripped before /api/v3.1'],
+ ['/api/v3.1/tools/execute/{tool_slug}', true, ''],
+ ['/api/v3.1/tools/execute/{tool_slug}/input', true, ''],
+ ['/api/v3.1/tools/scopes/required', true, 'v3.1-only; has no v3 counterpart'],
+ ['/api/v3/tools', true, ''],
+ ['/api/v3/tools/{tool_slug}', true, ''],
+ ['/api/v3/tools/execute/{tool_slug}', true, ''],
+ ['/api/v3/tools/execute/{tool_slug}/input', true, ''],
+ ['/api/v3.1/tools/enum', false, 'under /tools, not affected — breaks a prefix match'],
+ ['/api/v3.1/tools/execute/proxy', false, 'under /tools/execute, not affected'],
+ [
+ '/api/v3.1/tool_router/session/{session_id}/tools',
+ false,
+ 'ends in /tools — breaks a substring match',
+ ],
+ ['/api/v3.1/auth_configs', false, 'plain non-tool'],
+ ['/api/v3.1/triggers_types', false, 'triggers already default to latest'],
+ ['/tools/{tool_slug}', false, 'no version prefix; the predicate normalizes, it does not guess'],
+ ];
+
+ for (const [path, expected, why] of cases) {
+ test(`${path} -> ${expected}${why ? ` (${why})` : ''}`, () => {
+ expect(isToolVersionPath(path)).toBe(expected);
+ });
+ }
+});
diff --git a/docs/tests/static/content.test.ts b/docs/tests/static/content.test.ts
index dcf154ab8..f525f348b 100644
--- a/docs/tests/static/content.test.ts
+++ b/docs/tests/static/content.test.ts
@@ -114,6 +114,27 @@ describe("Content - provider compatibility", () => {
});
});
+describe("Content - Context7 ingest rules", () => {
+ test("context7.json states the current REST version without claiming route parity", async () => {
+ // Context7 ingests this repo for coding agents. Without a rule, nothing in
+ // the ingested corpus says which REST version is current.
+ const raw = await readFile(join(import.meta.dir, "../../../context7.json"), "utf-8");
+ const rules: unknown = JSON.parse(raw).rules;
+
+ expect(Array.isArray(rules)).toBe(true);
+ expect((rules as unknown[]).length).toBeGreaterThan(0);
+ expect(
+ (rules as string[]).some(rule => rule.includes("https://backend.composio.dev/api/v3.1")),
+ ).toBe(true);
+ expect(
+ (rules as string[]).some(rule =>
+ rule.includes("This version-default change is limited to these five endpoints."),
+ ),
+ ).toBe(true);
+ expect((rules as string[]).join("\n")).not.toMatch(/every non-tool endpoint.*unchanged/i);
+ });
+});
+
describe("Content - changelog validation", () => {
test("changelog files use MM-DD-YY naming pattern", async () => {
let entries;
diff --git a/docs/tests/static/llms-openapi.test.ts b/docs/tests/static/llms-openapi.test.ts
index 2dc3b6930..5196de668 100644
--- a/docs/tests/static/llms-openapi.test.ts
+++ b/docs/tests/static/llms-openapi.test.ts
@@ -1,18 +1,13 @@
import { beforeAll, describe, expect, mock, test } from "bun:test";
+import {
+ REST_VERSION_GUIDANCE,
+ TOOL_VERSION_GUIDANCE,
+} from "../../lib/api-version-guidance";
+import { SESSION_GUARDRAILS } from "../../lib/llm-guardrails";
+
let bundledSpec: Record<string, unknown> = {};
-mock.module("@/lib/source", () => ({
- source: {},
- getReferenceSource: async () => ({}),
- examplesSource: {},
- toolkitsSource: {},
- changelogEntries: [],
- slugToDate: () => null,
- formatDate: () => "",
- getLLMText: async () => "",
- mdxToCleanMarkdown: async () => "",
-}));
mock.module("next/navigation", () => ({
notFound: () => {
throw new Error("not found");
@@ -28,6 +23,8 @@ mock.module("@/lib/meta-tools-data", () => ({
getMetaToolBySlug: async () => null,
}));
mock.module("@/lib/toolkit-schema", () => ({
+ apiToolListSchema: { safeParse: (value: unknown) => ({ success: true, data: value }) },
+ apiTriggerListSchema: { safeParse: (value: unknown) => ({ success: true, data: value }) },
processSchema: (schema: unknown) => schema,
toolFromApi: (tool: unknown) => tool,
}));
@@ -185,6 +182,231 @@ describe("LLM OpenAPI markdown", () => {
});
});
+/**
+ * Version identity on operation pages.
+ *
+ * These are the pages that publish a complete working curl example, so they
+ * are the strongest signal an agent acts on — and they never touch
+ * mdxToCleanMarkdown, so a fix confined to lib/source.ts leaves them alone.
+ *
+ * Every fixture below uses production-shaped spec path keys — `/api/v3.1/…`
+ * and `/api/v3/…`, with the `/api` segment — because that is what the
+ * committed specs contain. The synthetic `/v3.1/test` keys in the fixtures
+ * above predate this and are deliberately left alone; do not copy their shape
+ * down here, or these tests will pass against an implementation that
+ * mis-normalizes production paths.
+ */
+describe("LLM OpenAPI markdown — API version identity", () => {
+ function specWith(pathKey: string) {
+ return {
+ paths: {
+ [pathKey]: {
+ get: {
+ summary: "Fixture operation",
+ responses: { 200: { description: "Success" } },
+ },
+ },
+ },
+ servers: [{ url: "https://backend.composio.dev" }],
+ };
+ }
+
+ function renderOperation(pageUrl: string, pathKey: string) {
+ bundledSpec = specWith(pathKey);
+ return openapiPageToMarkdown({
+ url: pageUrl,
+ data: {
+ title: "Fixture operation",
+ getOpenAPIPageProps: () => ({
+ payload: { bundled: bundledSpec },
+ operations: [{ path: pathKey, method: "GET" }],
+ }),
+ },
+ });
+ }
+
+ const V31_PAGE = "/reference/api-reference/auth-configs/getAuthConfigs";
+ const V30_PAGE = "/reference/v3/api-reference/auth-configs/getAuthConfigs";
+
+ test("a v3.1 operation page carries the current-version pointer above the endpoint line", async () => {
+ const markdown = await renderOperation(V31_PAGE, "/api/v3.1/auth_configs");
+
+ expect(markdown).toContain("**API version:**");
+ // Above **Endpoint:**, so a truncating reader still sees it.
+ expect(markdown.indexOf("**API version:**")).toBeLessThan(
+ markdown.indexOf("**Endpoint:**"),
+ );
+ });
+
+ test("a v3.0 operation page carries the legacy pointer and links its v3.1 page", async () => {
+ const markdown = await renderOperation(V30_PAGE, "/api/v3/auth_configs");
+
+ expect(markdown).toContain("**API version:**");
+ expect(markdown).toContain("v3.0");
+ expect(markdown).toContain(
+ "/reference/api-reference/auth-configs/getAuthConfigs.md",
+ );
+ expect(markdown.indexOf("**API version:**")).toBeLessThan(
+ markdown.indexOf("**Endpoint:**"),
+ );
+ });
+
+ test.each([
+ ["v3.1", V31_PAGE, "/api/v3.1/tools/{tool_slug}"],
+ ["v3.0", V30_PAGE, "/api/v3/tools/{tool_slug}"],
+ ])(
+ "a tool endpoint on %s carries both guidance constants exactly once",
+ async (_label, pageUrl, pathKey) => {
+ const markdown = await renderOperation(pageUrl, pathKey);
+
+ // The v3.1 case fails if the predicate strips /v3.1 without /api, or
+ // tries /api/v3 before /api/v3.1.
+ expect(markdown.split(REST_VERSION_GUIDANCE)).toHaveLength(2);
+ expect(markdown.split(TOOL_VERSION_GUIDANCE)).toHaveLength(2);
+ },
+ );
+
+ test("renders both GET-by-slug version parameters with the v3.1 runtime default", async () => {
+ const pathKey = "/api/v3.1/tools/{tool_slug}";
+ bundledSpec = {
+ paths: {
+ [pathKey]: {
+ get: {
+ parameters: [
+ { name: "version", in: "query", description: "Optional tool version" },
+ {
+ name: "toolkit_versions",
+ in: "query",
+ description: "Toolkit version specification",
+ },
+ ],
+ responses: { 200: { description: "Success" } },
+ },
+ },
+ },
+ };
+
+ const markdown = await openapiPageToMarkdown({
+ url: "/reference/api-reference/tools/getToolsByToolSlug",
+ data: {
+ title: "Get tool",
+ getOpenAPIPageProps: () => ({
+ payload: { bundled: bundledSpec },
+ operations: [{ path: pathKey, method: "GET" }],
+ }),
+ },
+ });
+
+ for (const parameter of ["version", "toolkit_versions"]) {
+ const line = markdown
+ .split("\n")
+ .find(candidate => candidate.startsWith(`- \`${parameter}\``));
+ expect(line).toContain("Defaults to `latest` when omitted on REST API v3.1.");
+ }
+ });
+
+ test.each([
+ [
+ "v3.1 execute",
+ "/reference/api-reference/tools/executeTool",
+ "/api/v3.1/tools/execute/{tool_slug}",
+ 'Tool version to execute (defaults to "00000000_00" if not specified)',
+ "latest",
+ "3.1",
+ ],
+ [
+ "v3.1 scopes",
+ "/reference/api-reference/tools/getRequiredScopes",
+ "/api/v3.1/tools/scopes/required",
+ "Toolkit version to resolve scopes against. Defaults to the pinned HTTP version when omitted.",
+ "latest",
+ "3.1",
+ ],
+ [
+ "v3 input generation",
+ "/reference/v3/api-reference/tools/generateToolInputs",
+ "/api/v3/tools/execute/{tool_slug}/input",
+ 'Tool version to use when generating inputs (defaults to "latest" if not specified)',
+ "00000000_00",
+ "3.0",
+ ],
+ ])(
+ "replaces the stale %s request-body description",
+ async (_label, pageUrl, pathKey, staleDescription, expectedDefault, apiVersion) => {
+ bundledSpec = {
+ paths: {
+ [pathKey]: {
+ post: {
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: {
+ type: "object",
+ properties: {
+ version: { type: "string", description: staleDescription },
+ },
+ },
+ },
+ },
+ },
+ responses: { 200: { description: "Success" } },
+ },
+ },
+ },
+ };
+
+ const markdown = await openapiPageToMarkdown({
+ url: pageUrl,
+ data: {
+ title: "Tool operation",
+ getOpenAPIPageProps: () => ({
+ payload: { bundled: bundledSpec },
+ operations: [{ path: pathKey, method: "POST" }],
+ }),
+ },
+ });
+ const versionLine = markdown.split("\n").find(line => line.startsWith("- `version`"));
+
+ expect(versionLine).toContain(
+ `Defaults to \`${expectedDefault}\` when omitted on REST API v${apiVersion}.`
+ );
+ expect(versionLine).not.toContain(staleDescription);
+ }
+ );
+
+ test("a non-tool endpoint carries the baseline and NOT the tool-version guidance", async () => {
+ const markdown = await renderOperation(V31_PAGE, "/api/v3.1/auth_configs");
+
+ expect(markdown).toContain(REST_VERSION_GUIDANCE);
+ expect(markdown).not.toContain(TOOL_VERSION_GUIDANCE);
+ });
+
+ test("a near-miss endpoint under /tools behaves like a non-tool endpoint", async () => {
+ // Under /tools, not one of the five — the case a prefix match gets wrong.
+ const markdown = await renderOperation(
+ "/reference/api-reference/tools/getToolsEnum",
+ "/api/v3.1/tools/enum",
+ );
+
+ expect(markdown).toContain(REST_VERSION_GUIDANCE);
+ expect(markdown).not.toContain(TOOL_VERSION_GUIDANCE);
+ });
+
+ test("neither page pulls in SESSION_GUARDRAILS", async () => {
+ // SESSION_GUARDRAILS composes TOOL_VERSION_GUIDANCE. If an operation page
+ // ever appended it, the tool-version text would arrive on every non-tool
+ // page through the back door and the scoping above would be theatre.
+ for (const [pageUrl, pathKey] of [
+ [V31_PAGE, "/api/v3.1/auth_configs"],
+ [V30_PAGE, "/api/v3/auth_configs"],
+ ]) {
+ const markdown = await renderOperation(pageUrl, pathKey);
+ expect(markdown).not.toContain(SESSION_GUARDRAILS);
+ expect(markdown).not.toContain("Instructions for AI Code Generators");
+ }
+ });
+});
+
describe("LLM page degradation", () => {
test("keeps a readable response when typed page parsing fails", () => {
expect(