@devries-cameron20 / composio Mirror · read-only / commits / 6e0a9db3c
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 16:00 UTC

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

This PR: - fixes [UXE-233](https://linear.app/composio/issue/UXE-233/docs-should-explicitly-direct-agents-to-use-v31-apis) - makes the agent-facing Markdown channels publish concrete REST v3.1 base URLs and endpoint tables while preserving the supported v3.0 reference tree - centralizes `REST_VERSION_GUIDANCE`, `TOOL_VERSION_GUIDANCE`, and raw-spec path matching in `lib/api-version-guidance.ts` - renders `ApiBaseUrl` and `ApiEndpointsTable` in authored MDX and adds an explicit version pointer to generated OpenAPI operation Markdown - separates current and legacy REST references in `llms.txt`, excludes v3.0 page bodies from `llms-full.txt`, and adds v3.1 selection guidance to Context7 - validates serialized `ApiEndpointsTable` payloads with Zod before generation while preserving forward-compatible fields - addresses review feedback for the renamed authentication page, SDK-reference pointer scope, generator validation behavior, and stale OpenAPI tool-version descriptions ## Context REST v3.0 is superseded but remains supported for existing integrations. This PR changes what new agent-generated code discovers first; it does not require existing v3.0 callers to migrate. Authenticated read-only probes against the deployed API confirmed that the affected v3 endpoints default to `00000000_00`, while their v3.1 counterparts default to `latest`. `POST /tools/scopes/required` is available only on v3.1 and defaults to `latest`. This PR does not move public URLs. A future `/reference/v3/` to `/reference/v3.0/` migration remains separate because it has independent compatibility and search-indexing risk. ## Verification - `bun test tests/static/` - `bun run build` - `bun run test:integration` - `bun run types:check` - `bun run lint` ## Review follow-up The version-default guidance is intentionally limited to the five verified tool endpoints. v3.1 is a structural superset of v3, so this PR does not claim route parity. Static coverage rejects broad non-tool parity wording in both the shared guidance and Context7 rules.

Alberto Schiabel committed Aug 7, 2026 at 18:48 UTC 6e0a9db3c7eb179a0dbe16a30ae37c37f89f76c9
21 files changed +1208 -54
context7.json
+6 -1
@@ -13,6 +13,11 @@
13 "CODE_OF_CONDUCT.md",
14 "code_of_conduct.md"
15 ],
16 - "rules": [],
16 + "rules": [
17 + "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.",
18 + "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.",
19 + "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.",
20 + "TypeScript (@composio/core) and Python (composio) SDK callers are already on v3.1 through the generated client; this only affects direct REST calls."
21 + ],
22 "previousVersions": []
23 }
docs/agent-guidance/context/api-reference.md
+53
@@ -92,6 +92,59 @@ components/api-endpoints-table.tsx ← Endpoint tables in index pages, shows ver
92 components/version-badge.tsx ← Badge on endpoint pages showing API version
93 ```
94
95 +Markdown channels (what agents read — see "Version identity in the markdown
96 +channels" below):
97 +
98 +```
99 +lib/source.ts ← mdxToCleanMarkdown renders ApiBaseUrl + ApiEndpointsTable for .md
100 +app/llms.mdx/[[...slug]]/route.ts ← openapiPageToMarkdown emits the version pointer + guidance
101 +lib/api-endpoints-table-schema.ts ← shared zod schema for the ApiEndpointsTable prop
102 +lib/api-version-guidance.ts ← the two guidance constants + the tool-path predicate
103 +```
104 +
105 +### Version identity in the markdown channels
106 +
107 +The signals that separate v3.1 from v3.0 (version dropdown, base URL, endpoint
108 +tables, version badge) all live in the **browser** rendering path. Agents read
109 +`.md`, `llms.txt`, `llms-full.txt`, and the Context7 ingest, none of which walk
110 +that path — so every one of those signals used to be dropped, and the only
111 +concrete request an agent could find was a v3.0 curl example.
112 +
113 +There are **two markdown renderers**, and they fail differently:
114 +
115 +| Surface | Renderer |
116 +|---------|----------|
117 +| MDX pages under `/reference/**` (incl. `reference.md`, tag pages) | `getLLMText` + `mdxToCleanMarkdown` in `lib/source.ts` |
118 +| OpenAPI operation pages (e.g. `getTools.md`) | `openapiPageToMarkdown` in `app/llms.mdx/[[...slug]]/route.ts` |
119 +
120 +A fix in `lib/source.ts` alone does not reach operation pages.
121 +
122 +**Composition rule** — the rule most likely to be violated by the next person
123 +adding a channel:
124 +
125 +- **Broad channels** (`SESSION_GUARDRAILS`, `DIRECT_EXECUTION_GUARDRAILS`)
126 + compose **both** `REST_VERSION_GUIDANCE` and `TOOL_VERSION_GUIDANCE`. Their
127 + reader may call any endpoint.
128 +- **OpenAPI operation pages** get `REST_VERSION_GUIDANCE` always, and
129 + `TOOL_VERSION_GUIDANCE` only when `isToolVersionPath` matches. They do **not**
130 + get `SESSION_GUARDRAILS` — it is about SDK code generation, and since it
131 + composes the tool-version text it would force it onto operations it does not
132 + apply to.
133 +- **Top notes** (`getLLMText`, `openapiPageToMarkdown`) carry **neither**. They
134 + are a pointer only: which version, the base URL, the cross-version link. The
135 + guidance already appears further down the same response.
136 +
137 +Two more rules:
138 +
139 +- **Any new version-dependent rendering must go through `detectApiVersion`**
140 + (`lib/api-version.ts`), never an inline `/reference/v3/` string test. Moving
141 + the legacy tree's URL should be a one-line change in that file.
142 +- **Normalization is `isToolVersionPath`'s job, and only its job.** Callers pass
143 + the raw spec path key verbatim (`/api/v3.1/tools/{tool_slug}`, with the `/api`
144 + segment). It strips `/api/v3.1` before `/api/v3` and compares by exact set
145 + membership — `/tools/enum`, `/tools/execute/proxy`, and
146 + `tool_router/…/tools` all mention `tools` and none of them is affected.
147 +
148 ### Content structure
149
150 v3.0 has its own complete page tree under `content/reference/v3/`:
docs/app/llms-full.txt/route.ts
+4 -2
@@ -7,6 +7,7 @@ import {
7 type LLMPage,
8 } from '@/lib/source';
9 import { SESSION_GUARDRAILS } from '@/lib/llm-guardrails';
10 +import { detectReferenceApiVersion } from '@/lib/api-version';
11 import type { ReactNode } from 'react';
12
13 export const revalidate = false;
@@ -122,7 +123,6 @@ async function getTextForPages(pages: PageLike[]) {
123 includeGuardrails: false,
124 });
125 } catch {
125 - // Graceful fallback if getText fails
126 return `# ${page.data.title} (${page.url})\n\n${page.data.description || ''}`;
127 }
128 })
@@ -141,7 +141,9 @@ export async function GET() {
141 const [docsResults, examplesResults, referenceResults, toolkitsResults] = await Promise.all([
142 getTextForPages(orderedDocsPages),
143 getTextForPages(examplesSource.getPages()),
144 - getTextForPages(referenceSource.getPages()),
144 + getTextForPages(
145 + referenceSource.getPages().filter(page => detectReferenceApiVersion(page.url) !== '3.0')
146 + ),
147 getTextForPages(toolkitsSource.getPages()),
148 ]);
149
docs/app/llms.mdx/[[...slug]]/route.ts
+59 -2
@@ -11,6 +11,13 @@ import {
11 type LLMPage,
12 } from '@/lib/source';
13 import { dereferenceDocument } from '@/lib/openapi-deref';
14 +import {
15 + REST_VERSION_GUIDANCE,
16 + TOOL_VERSION_GUIDANCE,
17 + apiVersionPointer,
18 + isToolVersionPath,
19 + toolVersionParameterDescription,
20 +} from '@/lib/api-version-guidance';
21 import { notFound } from 'next/navigation';
22 import { readFile } from 'fs/promises';
23 import { join } from 'path';
@@ -372,6 +379,23 @@ function renderSchema(schema: OpenAPISchema, indent = 0, maxDepth = 4, depth = 0
379 return lines;
380 }
381
382 +/** Overrides only the top-level request-body version field for affected tool operations. */
383 +function withToolVersionDescription(rawSpecPath: string, schema: OpenAPISchema): OpenAPISchema {
384 + const versionProperty = schema.properties?.version;
385 + if (!versionProperty || !isToolVersionPath(rawSpecPath)) return schema;
386 +
387 + return {
388 + ...schema,
389 + properties: {
390 + ...schema.properties,
391 + version: {
392 + ...versionProperty,
393 + description: toolVersionParameterDescription(rawSpecPath, versionProperty.description),
394 + },
395 + },
396 + };
397 +}
398 +
399 // Get a readable type string
400 function getTypeString(schema: OpenAPISchema, depth = 0, maxDepth = 4): string {
401 if (depth > maxDepth) return '...';
@@ -451,6 +475,15 @@ export async function openapiPageToMarkdown(page: {
475 const lines: string[] = [`# ${title}`, ''];
476 lines.push(`**Documentation:** ${page.url}`, '');
477
478 + // Which REST version this page documents, emitted above the `**Endpoint:**`
479 + // line below so a truncating reader still sees it. These pages publish a
480 + // complete working curl example and never touch mdxToCleanMarkdown, so
481 + // without this the strongest v3 signal in the corpus stays unlabelled.
482 + const versionPointer = apiVersionPointer(page.url);
483 + if (versionPointer) {
484 + lines.push(versionPointer.trim(), '');
485 + }
486 +
487 if (description) {
488 lines.push(description, '');
489 }
@@ -548,7 +581,12 @@ export async function openapiPageToMarkdown(page: {
581 for (const param of queryParams) {
582 const typeStr = getTypeString(param.schema || { type: 'string' });
583 const reqMark = param.required ? ' *(required)*' : '';
551 - lines.push(`- \`${param.name}\` (${typeStr})${reqMark}: ${param.description || ''}`);
584 + const description =
585 + (param.name === 'version' || param.name === 'toolkit_versions') &&
586 + isToolVersionPath(name)
587 + ? toolVersionParameterDescription(name, param.description)
588 + : param.description || '';
589 + lines.push(`- \`${param.name}\` (${typeStr})${reqMark}: ${description}`);
590 }
591 lines.push('');
592 }
@@ -573,8 +611,9 @@ export async function openapiPageToMarkdown(page: {
611 }
612 const schema = operation.requestBody.content['application/json'].schema;
613 if (schema) {
614 + const renderedSchema = withToolVersionDescription(name, schema);
615 lines.push('**Schema:**', '');
577 - lines.push(...renderSchema(schema));
616 + lines.push(...renderSchema(renderedSchema));
617 lines.push('');
618
619 // Example
@@ -623,6 +662,24 @@ export async function openapiPageToMarkdown(page: {
662 }
663 }
664
665 + // Guidance goes after the operation body. Operation pages deliberately do
666 + // NOT receive SESSION_GUARDRAILS: that block is about SDK code generation,
667 + // it would be noise on a REST operation page, and — because it composes
668 + // TOOL_VERSION_GUIDANCE — it would force the tool-version text onto every
669 + // operation regardless of scope.
670 + //
671 + // The baseline applies to every operation. The tool-version note applies to
672 + // exactly the five endpoints whose version default changes, decided by
673 + // isToolVersionPath on the RAW spec path key (`/api/v3.1/tools/{tool_slug}`)
674 + // — normalization belongs to the predicate, so nothing is stripped here and
675 + // nothing keys off the page URL.
676 + if (selectedOperations.length > 0) {
677 + lines.push('---', '', REST_VERSION_GUIDANCE);
678 + if (selectedOperations.some(selected => isToolVersionPath(selected.name))) {
679 + lines.push('', TOOL_VERSION_GUIDANCE);
680 + }
681 + }
682 +
683 return lines.join('\n').trim();
684 }
685
docs/app/llms.txt/route.ts
+46 -3
@@ -1,4 +1,5 @@
1 import { source, examplesSource, referenceSource, toolkitsSource } from '@/lib/source';
2 +import { detectReferenceApiVersion } from '@/lib/api-version';
3 import type { ReactNode } from 'react';
4
5 export const revalidate = false;
@@ -99,13 +100,51 @@ function formatPage(page: { url: string }) {
100 return `- https://docs.composio.dev${page.url}.md`;
101 }
102
103 +/**
104 + * Splits reference pages by REST version.
105 + *
106 + * This list is built with a flat `.map(formatPage)` that bypasses the
107 + * `isLegacySeparator` filter the guides tree gets, so the two trees used to
108 + * arrive interleaved under one unlabelled heading — and `/reference/v3/` is
109 + * the only version-shaped path in the corpus, so it is the highest-precision
110 + * match for the query most readers intend as "current Composio".
111 + *
112 + * Partitioned with `detectApiVersion`, not a literal path test, so moving the
113 + * legacy tree's URL stays a one-line change in `lib/api-version.ts`.
114 + */
115 +function partitionByApiVersion<T extends { url: string }>(pages: T[]) {
116 + const current: T[] = [];
117 + const legacy: T[] = [];
118 + const versionIndependent: T[] = [];
119 + for (const page of pages) {
120 + const version = detectReferenceApiVersion(page.url);
121 + if (version === '3.0') legacy.push(page);
122 + else if (version === '3.1') current.push(page);
123 + else versionIndependent.push(page);
124 + }
125 + return { current, legacy, versionIndependent };
126 +}
127 +
128 export async function GET() {
129 try {
130 const docsTree = walkPageTree(source.pageTree.children as TreeNode[]);
131
132 const examplesPages = examplesSource.getPages();
107 - const referencePages = referenceSource.getPages();
133 const toolkitsPages = toolkitsSource.getPages();
134 + const {
135 + current: currentReferencePages,
136 + legacy: legacyReferencePages,
137 + versionIndependent: versionIndependentReferencePages,
138 + } = partitionByApiVersion(referenceSource.getPages());
139 +
140 + const legacyReferenceSection =
141 + legacyReferencePages.length > 0
142 + ? `
143 +## API Reference (v3.0, legacy — supported, not for new code)
144 +
145 +${legacyReferencePages.map(formatPage).join('\n')}
146 +`
147 + : '';
148
149 const index = `# Composio Documentation
150
@@ -119,9 +158,13 @@ ${docsTree}
158
159 ${examplesPages.map(formatPage).join('\n')}
160
122 -## API Reference
161 +## API Reference (v3.1, current)
162 +
163 +${currentReferencePages.map(formatPage).join('\n')}
164 +${legacyReferenceSection}
165 +## SDK and product reference (version-independent)
166
124 -${referencePages.map(formatPage).join('\n')}
167 +${versionIndependentReferencePages.map(formatPage).join('\n')}
168
169 ## Toolkits
170
docs/components/api-base-url.tsx
+5 -6
@@ -1,18 +1,17 @@
1 'use client';
2
3 import { useApiVersion } from '@/lib/use-api-version';
4 -
5 -const BASE_URLS: Record<string, string> = {
6 - '3.1': 'https://backend.composio.dev/api/v3.1',
7 - '3.0': 'https://backend.composio.dev/api/v3',
8 -};
4 +import { API_BASE_URLS } from '@/lib/api-version';
5
6 /**
7 * Renders the API base URL for the currently selected version.
8 * Detects version from URL path (/reference/v3/ = v3.0, otherwise v3.1).
9 + *
10 + * The `.md` channel renders this tag through `mdxToCleanMarkdown`, which reads
11 + * the same `API_BASE_URLS` map — the browser and the agent see one URL.
12 */
13 export function ApiBaseUrl() {
14 const version = useApiVersion();
16 - return <code>{BASE_URLS[version] ?? BASE_URLS['3.1']}</code>;
15 + return <code>{API_BASE_URLS[version] ?? API_BASE_URLS['3.1']}</code>;
16 }
17
docs/components/api-endpoints-table.tsx
+5 -12
@@ -3,23 +3,16 @@
3 import { useApiVersion } from '@/lib/use-api-version';
4 import { DeprecatedApiLegacyBadge } from '@/components/legacy-badge';
5 import { getApiDisplayTitle } from '@/lib/api-deprecation';
6 -
7 -interface Endpoint {
8 - method: string;
9 - pathV31: string;
10 - pathV3: string;
11 - summary: string;
12 - href: string;
13 - /** Set by the generator for operations flagged `deprecated` in the OpenAPI
14 - * spec. Surfaced with the existing "Legacy" tag (see components/legacy-badge.tsx). */
15 - legacy?: boolean;
16 -}
6 +import type { ApiEndpoint } from '@/lib/api-endpoints-table-schema';
7
8 /**
9 * Renders an endpoint table that updates based on the selected API version.
10 * Used in auto-generated index pages.
11 + *
12 + * The prop shape lives in `lib/api-endpoints-table-schema.ts` — one type, one
13 + * source, shared with the `.md` converter and the generator's validation.
14 */
22 -export function ApiEndpointsTable({ endpoints }: { endpoints: Endpoint[] }) {
15 +export function ApiEndpointsTable({ endpoints }: { endpoints: ApiEndpoint[] }) {
16 const version = useApiVersion();
17
18 return (
docs/lib/api-endpoints-table-schema.ts new
+34
@@ -0,0 +1,34 @@
1 +import { z } from 'zod';
2 +
3 +/**
4 + * The `endpoints={[...]}` prop of `<ApiEndpointsTable />`.
5 + *
6 + * `scripts/generate-api-index.ts` serializes this array into MDX as a JSON
7 + * string, so every reader — the React component, the `.md` converter in
8 + * `lib/source.ts`, and the route guard in
9 + * `tests/static/api-reference-routes.test.ts` — is reading external data and
10 + * parses it here once, with `z.infer` flowing downstream.
11 + *
12 + * Deliberately non-strict: unknown keys are stripped rather than rejected, so
13 + * adding a field to the generator does not break rendering on pages generated
14 + * before the field existed.
15 + */
16 +export const apiEndpointSchema = z.object({
17 + method: z.string(),
18 + /** Path under the current prefix, e.g. `/api/v3.1/tools/{tool_slug}`. */
19 + pathV31: z.string(),
20 + /** Same operation under the previous prefix, e.g. `/api/v3/tools/{tool_slug}`. */
21 + pathV3: z.string(),
22 + summary: z.string(),
23 + href: z.string(),
24 + /**
25 + * Set by the generator for operations flagged `deprecated` in the OpenAPI
26 + * spec. Surfaced with the existing "Legacy" tag (see
27 + * `components/legacy-badge.tsx`).
28 + */
29 + legacy: z.boolean().optional(),
30 +});
31 +
32 +export const apiEndpointsSchema = z.array(apiEndpointSchema);
33 +
34 +export type ApiEndpoint = z.infer<typeof apiEndpointSchema>;
docs/lib/api-version-guidance.ts new
+96
@@ -0,0 +1,96 @@
1 +/** Shared version guidance for agent-facing markdown. */
2 +
3 +import {
4 + API_BASE_URLS,
5 + detectApiVersion,
6 + isReferenceUrl,
7 + toCurrentVersionUrl,
8 +} from './api-version';
9 +
10 +/** Baseline guidance for all REST operations. */
11 +export const REST_VERSION_GUIDANCE = `## REST API version
12 +
13 +The current REST API version is **v3.1**, served at \`${API_BASE_URLS['3.1']}\`. Prefer it for new code and new examples.
14 +
15 +\`${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.`;
16 +
17 +/** Version-stripped tool paths whose defaults need explicit guidance. */
18 +export const TOOL_VERSION_PATHS = [
19 + '/tools',
20 + '/tools/{tool_slug}',
21 + '/tools/execute/{tool_slug}',
22 + '/tools/execute/{tool_slug}/input',
23 + '/tools/scopes/required',
24 +] as const;
25 +
26 +/** Guidance for the tool-endpoint defaults that differ across REST versions. */
27 +export const TOOL_VERSION_GUIDANCE = `## Tool-endpoint version defaults on v3.1
28 +
29 +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.
30 +
31 +| Endpoint | Version parameter |
32 +| --- | --- |
33 +| \`GET /tools\` | \`toolkit_versions\` (query) |
34 +| \`GET /tools/{tool_slug}\` | \`version\` or \`toolkit_versions\` (query) |
35 +| \`POST /tools/execute/{tool_slug}\` | \`version\` (body) |
36 +| \`POST /tools/execute/{tool_slug}/input\` | \`version\` (body) |
37 +| \`POST /tools/scopes/required\` | \`version\` (body) |
38 +
39 +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.
40 +
41 +This version-default change is limited to the five endpoints above.`;
42 +
43 +const TOOL_VERSION_PATH_SET: ReadonlySet<string> = new Set(TOOL_VERSION_PATHS);
44 +
45 +/** Longest prefix first to avoid matching `/api/v3` inside `/api/v3.1`. */
46 +const VERSION_PREFIXES = ['/api/v3.1', '/api/v3'] as const;
47 +
48 +/**
49 + * Replaces stale OpenAPI default prose with the deployed REST-version default.
50 + * The source specs are generated upstream, so the agent-facing renderer fixes
51 + * their description without mutating the generated snapshots.
52 + */
53 +export function toolVersionParameterDescription(
54 + rawSpecPath: string,
55 + description = 'Tool version to use'
56 +): string {
57 + if (!isToolVersionPath(rawSpecPath)) return description;
58 +
59 + const apiVersion = rawSpecPath.startsWith('/api/v3.1') ? '3.1' : '3.0';
60 + const defaultVersion = apiVersion === '3.1' ? 'latest' : '00000000_00';
61 + const withoutDefault = description.replace(/\s*\(?defaults?\s+to\b[\s\S]*$/i, '').trim();
62 + const base = (withoutDefault || 'Tool version to use').replace(/[.:]\s*$/, '');
63 +
64 + return `${base}. Defaults to \`${defaultVersion}\` when omitted on REST API v${apiVersion}.`;
65 +}
66 +
67 +/**
68 + * The short version pointer for a reference page: which version this page
69 + * documents, its base URL, and — on a legacy page — the link to the same page
70 + * on v3.1. Empty outside the reference tree.
71 + *
72 + * A pointer, not guidance: the guardrail block (MDX pages) or
73 + * `REST_VERSION_GUIDANCE` (operation pages) already carries the explanation
74 + * further down the same response, and repeating it would put the same
75 + * paragraph twice. Both renderers call this so their pointers agree by
76 + * construction.
77 + */
78 +export function apiVersionPointer(pageUrl: string): string {
79 + if (!isReferenceUrl(pageUrl)) return '';
80 +
81 + if (detectApiVersion(pageUrl) === '3.0') {
82 + const currentUrl = `${toCurrentVersionUrl(pageUrl)}.md`;
83 + 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`;
84 + }
85 +
86 + 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`;
87 +}
88 +
89 +export function isToolVersionPath(rawSpecPath: string): boolean {
90 + for (const prefix of VERSION_PREFIXES) {
91 + if (rawSpecPath.startsWith(prefix)) {
92 + return TOOL_VERSION_PATH_SET.has(rawSpecPath.slice(prefix.length));
93 + }
94 + }
95 + return false;
96 +}
docs/lib/api-version.ts
+46
@@ -4,6 +4,19 @@
4 */
5
6 export type ApiVersion = '3.1' | '3.0';
7 +export type ReferenceApiVersion = ApiVersion | null;
8 +
9 +/**
10 + * REST base URL per API version. Single source of truth — the browser
11 + * component (`components/api-base-url.tsx`), the markdown converter
12 + * (`lib/source.ts`), and the version guidance constants
13 + * (`lib/api-version-guidance.ts`) all read it from here rather than
14 + * spelling the URL out again.
15 + */
16 +export const API_BASE_URLS: Record<ApiVersion, string> = {
17 + '3.1': 'https://backend.composio.dev/api/v3.1',
18 + '3.0': 'https://backend.composio.dev/api/v3',
19 +};
20
21 /**
22 * Detects the API version from a pathname.
@@ -14,3 +27,36 @@ export function detectApiVersion(pathname: string): ApiVersion {
27 ? '3.0'
28 : '3.1';
29 }
30 +
31 +/** True for reference pages that describe the REST API. */
32 +export function isReferenceUrl(pathname: string): boolean {
33 + return (
34 + pathname !== '/reference/glossary' &&
35 + pathname !== '/reference/sdk-reference' &&
36 + !pathname.startsWith('/reference/sdk-reference/') &&
37 + (pathname === '/reference' || pathname.startsWith('/reference/'))
38 + );
39 +}
40 +
41 +/** The REST version described by a reference page, or null for SDK/glossary pages. */
42 +export function detectReferenceApiVersion(pathname: string): ReferenceApiVersion {
43 + return isReferenceUrl(pathname) ? detectApiVersion(pathname) : null;
44 +}
45 +
46 +const CURRENT_VERSION_URLS: Record<string, string> = {
47 + '/reference/v3/authentication': '/reference/authenticating-to-composio',
48 +};
49 +
50 +/**
51 + * The current-version URL for a legacy-tree page, so an agent reading a v3.0
52 + * page can be pointed at the same operation on v3.1. Any other pathname is
53 + * returned unchanged.
54 + */
55 +export function toCurrentVersionUrl(pathname: string): string {
56 + if (CURRENT_VERSION_URLS[pathname]) return CURRENT_VERSION_URLS[pathname];
57 + if (pathname === '/reference/v3') return '/reference';
58 + if (pathname.startsWith('/reference/v3/')) {
59 + return `/reference/${pathname.slice('/reference/v3/'.length)}`;
60 + }
61 + return pathname;
62 +}
docs/lib/llm-guardrails/direct-execution.ts
+12
@@ -1,8 +1,12 @@
1 import { TERMINOLOGY_MIGRATION } from './terminology';
2 +import { REST_VERSION_GUIDANCE, TOOL_VERSION_GUIDANCE } from '../api-version-guidance';
3
4 /**
5 * Guardrails for pages tagged with llmGuardrails: "direct-execution".
6 * Concise rules + key patterns for LLMs generating direct execution code.
7 + *
8 + * Broad channel, so it composes both version guidance constants — interpolated
9 + * from `lib/api-version-guidance.ts`, never retyped.
10 */
11 export const DIRECT_EXECUTION_GUARDRAILS = `
12
@@ -78,5 +82,13 @@ const result = await composio.tools.execute("GITHUB_CREATE_ISSUE", {
82 4. **Provider at init** — \`Composio(provider=OpenAIProvider())\` in Python, \`new Composio({ provider: new OpenAIProvider() })\` in TypeScript. Defaults to OpenAI if omitted.
83 5. **Correct provider imports** — \`composio_<provider>\` for Python, \`@composio/<provider>\` for TypeScript. For OpenAI Agents SDK use \`composio_openai_agents\` / \`@composio/openai-agents\`.
84 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>"\`.
85 +
86 +---
87 +
88 +# Calling the REST API directly
89 +
90 +${REST_VERSION_GUIDANCE}
91 +
92 +${TOOL_VERSION_GUIDANCE}
93 ${TERMINOLOGY_MIGRATION}
94 `;
docs/lib/llm-guardrails/session.ts
+14
@@ -1,4 +1,5 @@
1 import { TERMINOLOGY_MIGRATION } from './terminology';
2 +import { REST_VERSION_GUIDANCE, TOOL_VERSION_GUIDANCE } from '../api-version-guidance';
3
4 /**
5 * Default integration notes appended to most pages.
@@ -8,6 +9,11 @@ import { TERMINOLOGY_MIGRATION } from './terminology';
9 * (Rewritten after two eval rounds showed capable agents classify
10 * ALWAYS/NEVER-style instruction blocks as prompt injection and distrust the
11 * page they appear on.)
12 + *
13 + * A reader of a session guide may call any endpoint, so this is a broad
14 + * channel: it composes both version guidance constants. They are interpolated
15 + * from `lib/api-version-guidance.ts`, never retyped — see the composition rule
16 + * there.
17 */
18 export const SESSION_GUARDRAILS = `
19
@@ -60,5 +66,13 @@ Use \`session.mcp.url\` and \`session.mcp.headers\` with any MCP-compatible clie
66 - 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.
67 - 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).
68 - **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).
69 +
70 +---
71 +
72 +# 3. Calling the REST API directly
73 +
74 +${REST_VERSION_GUIDANCE}
75 +
76 +${TOOL_VERSION_GUIDANCE}
77 ${TERMINOLOGY_MIGRATION}
78 `;
docs/lib/search-index.ts
+1 -1
@@ -332,7 +332,7 @@ function recordsFromMarkdownPage(input: {
332 const isLegacy = input.legacy === true;
333 const resolvedPageRank = isLegacy ? LEGACY_PAGE_RANK : pageRank(input.url, input.type);
334 const resolvedTags = isLegacy ? [...(input.tags ?? []), 'legacy'] : input.tags;
335 - const clean = mdxToCleanMarkdown(input.markdown);
335 + const clean = mdxToCleanMarkdown(input.markdown, input.url);
336 const lines = clean.split('\n');
337 const headingSlugs = new Map<string, number>();
338 const headings: string[] = [];
docs/lib/source.ts
+110 -3
@@ -8,6 +8,9 @@ import { HIDDEN_API_TAGS } from './filter-api-version';
8 import { FILE_BUILDS } from './file-builds';
9 import { replaceRepoBrowserMarkdown } from './repo-browser-markdown';
10 import { transformDeprecatedApiSidebarNode } from './deprecated-api-sidebar';
11 +import { API_BASE_URLS, detectApiVersion, type ApiVersion } from './api-version';
12 +import { apiVersionPointer } from './api-version-guidance';
13 +import { apiEndpointsSchema } from './api-endpoints-table-schema';
14
15 /**
16 * True if a reference URL belongs to an intentionally-hidden API tag
@@ -149,16 +152,115 @@ export function getOgImageUrl(
152 return `https://og.composio.dev/api/og?title=${encodedTitle}`;
153 }
154
155 +/**
156 + * `<ApiEndpointsTable />` reaches this converter in two different shapes.
157 + *
158 + * `getLLMText` reads fumadocs' *processed* markdown, which re-serializes the
159 + * JSX expression attribute as a quoted string with the inner quotes escaped:
160 + *
161 + * <ApiEndpointsTable endpoints="[{&#x22;method&#x22;:&#x22;GET&#x22;, ...}]" />
162 + *
163 + * while `lib/search-index.ts` passes the raw file content, which keeps the
164 + * authored form:
165 + *
166 + * <ApiEndpointsTable endpoints={[{"method":"GET", ...}]} />
167 + *
168 + * Matching only the authored form is what left the Endpoints section empty on
169 + * every live tag page, so both are matched here. Braces are not escaped in the
170 + * processed form, and every inner `"` is — so a non-greedy match to the next
171 + * unescaped quote is exact.
172 + */
173 +const API_ENDPOINTS_TABLE_REGEX =
174 + /<ApiEndpointsTable\s+endpoints=(?:\{([\s\S]*?)\}\s*\/>|"([\s\S]*?)"\s*\/>)/g;
175 +
176 +/** Reverses the entity escaping fumadocs applies to JSX attribute values. */
177 +function decodeHtmlEntities(value: string): string {
178 + return value
179 + .replace(/&#x([0-9a-fA-F]+);/g, (_, hex: string) =>
180 + String.fromCodePoint(Number.parseInt(hex, 16))
181 + )
182 + .replace(/&#(\d+);/g, (_, dec: string) => String.fromCodePoint(Number.parseInt(dec, 10)))
183 + .replace(/&quot;/g, '"')
184 + .replace(/&apos;/g, "'")
185 + .replace(/&lt;/g, '<')
186 + .replace(/&gt;/g, '>')
187 + .replace(/&amp;/g, '&');
188 +}
189 +
190 +/**
191 + * Renders an `<ApiEndpointsTable />` payload as a markdown table.
192 + *
193 + * Degrades rather than throws: a malformed payload emits nothing for that one
194 + * table and warns, because taking the whole `.md` response down over one bad
195 + * page is worse. The failure signal for checked-in content lives in the static
196 + * suite instead — `tests/static/api-reference-routes.test.ts` runs every
197 + * committed payload through the same schema, and
198 + * `scripts/generate-api-index.ts` refuses to write an invalid one.
199 + */
200 +function endpointsTableToMarkdown(payload: string, version: ApiVersion, url?: string): string {
201 + const where = url ?? '(no page url)';
202 +
203 + let json: unknown;
204 + try {
205 + json = JSON.parse(payload);
206 + } catch {
207 + console.warn(`[mdxToCleanMarkdown] unparseable ApiEndpointsTable payload on ${where}`);
208 + return '';
209 + }
210 +
211 + const parsed = apiEndpointsSchema.safeParse(json);
212 + if (!parsed.success) {
213 + console.warn(`[mdxToCleanMarkdown] invalid ApiEndpointsTable payload on ${where}`);
214 + return '';
215 + }
216 +
217 + const rows = parsed.data.map(endpoint => {
218 + const path = version === '3.0' ? endpoint.pathV3 : endpoint.pathV31;
219 + const summary = endpoint.summary
220 + .replace(/\\/g, '\\\\')
221 + .replace(/\|/g, '\\|')
222 + .replace(/\n/g, ' ');
223 + const label = endpoint.legacy ? `${summary} (Legacy)` : summary;
224 + return `| \`${endpoint.method}\` | \`${path}\` | [${label}](${endpoint.href}) |`;
225 + });
226 +
227 + return ['| Method | Path | Endpoint |', '| --- | --- | --- |', ...rows].join('\n');
228 +}
229 +
230 /**
231 * Converts MDX content to clean markdown for AI agents.
232 * Strips JSX components and converts them to plain text equivalents.
233 + *
234 + * `url` is the page URL. `ApiBaseUrl` and `ApiEndpointsTable` are client
235 + * components that pick a version from `usePathname()`, which the `.md` channel
236 + * has no access to — so the URL is passed in and resolved with the same
237 + * `detectApiVersion`. Optional because the changelog call sites have no page
238 + * URL; with none, the page is treated as current (v3.1), which is correct
239 + * there since the changelog tree is not versioned.
240 */
156 -export function mdxToCleanMarkdown(content: string): string {
241 +export function mdxToCleanMarkdown(content: string, url?: string): string {
242 let result = content;
243 + const version = url ? detectApiVersion(url) : '3.1';
244
245 // Remove frontmatter
246 result = result.replace(/^---[\s\S]*?---\n*/m, '');
247
248 + // Version-dependent API components. These must run before the generic JSX
249 + // strippers at the bottom of this function, which would otherwise drop both
250 + // tags — publishing an empty `Base URL` bullet and an empty `Endpoints`
251 + // section to every agent while the superseded v3.0 operation pages published
252 + // a complete working request. That asymmetry is why agents reached for v3.
253 + result = result.replace(/<ApiBaseUrl\s*\/>/g, `\`${API_BASE_URLS[version]}\``);
254 + result = result.replace(
255 + API_ENDPOINTS_TABLE_REGEX,
256 + (_, bracedPayload?: string, quotedPayload?: string) =>
257 + endpointsTableToMarkdown(
258 + bracedPayload ?? decodeHtmlEntities(quotedPayload ?? ''),
259 + version,
260 + url
261 + )
262 + );
263 +
264 // Convert YouTube to link
265 result = result.replace(
266 /<YouTube\s+id="([^"]+)"\s+title="([^"]+)"\s*\/>/g,
@@ -459,7 +561,7 @@ ${page.data.description || ''}`;
561 }
562 segments.push(content.slice(lastIndex));
563
462 - const cleanSegments = segments.map(s => mdxToCleanMarkdown(s));
564 + const cleanSegments = segments.map(s => mdxToCleanMarkdown(s, page.url));
565 let cleanContent = cleanSegments[0];
566 for (let i = 0; i < mermaidCharts.length; i++) {
567 const chart = mermaidCharts[i]
@@ -479,12 +581,17 @@ ${page.data.description || ''}`;
581 // legacy guide contradicts the guide's own (older) content.
582 const isLegacy = page.data.legacy === true;
583 const written = page.data.written;
482 - const topNote = isLegacy
584 + const frontmatterNote = isLegacy
585 ? `\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`
586 : written
587 ? `\n> _Written ${written}._\n`
588 : '';
589
590 + // Which REST version this page documents. Scoped to the reference tree —
591 + // /docs/** has no REST version — and carries no guidance paragraph, because
592 + // the guardrail block further down this same response already does.
593 + const topNote = `${frontmatterNote}${apiVersionPointer(page.url)}`;
594 +
595 const guardrails = includeGuardrails && !isLegacy ? getGuardrails(page.data.llmGuardrails) : '';
596
597 return `# ${page.data.title} (${page.url})
docs/scripts/generate-api-index.ts
+29 -9
@@ -8,7 +8,29 @@
8
9 import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, readdirSync } from 'fs';
10 import { join } from 'path';
11 +import { z } from 'zod';
12 import { HIDDEN_API_TAGS } from '../lib/filter-api-version';
13 +import { apiEndpointsSchema } from '../lib/api-endpoints-table-schema';
14 +
15 +/**
16 + * Serializes an endpoints array for the `<ApiEndpointsTable />` prop, refusing
17 + * to write a payload the readers cannot parse.
18 + *
19 + * At runtime `mdxToCleanMarkdown` degrades a malformed payload to an empty
20 + * table (one bad page must not 500 the whole `.md` response), so an invalid
21 + * payload written here would render as a silently empty Endpoints section —
22 + * exactly the defect this pipeline exists to avoid. A generator that cannot
23 + * produce a valid payload should fail the generation run instead.
24 + */
25 +function serializeEndpoints(endpoints: unknown, label: string): string {
26 + const parsed = apiEndpointsSchema.safeParse(endpoints);
27 + if (!parsed.success) {
28 + throw new Error(
29 + `Invalid ApiEndpointsTable payload for ${label}:\n${z.prettifyError(parsed.error)}`
30 + );
31 + }
32 + return JSON.stringify(endpoints);
33 +}
34
35 /**
36 * API-reference tags hidden on our side even though the upstream OpenAPI spec
@@ -263,16 +285,14 @@ function generateIndexPages() {
285
286 let v3Ops: Record<string, OperationEntry[]> = {};
287 if (existsSync(specV3Path)) {
266 - const specV3: OpenAPISpec = JSON.parse(readFileSync(specV3Path, 'utf-8'));
267 - v3Ops = getOperationsByTag(specV3);
288 + const loadedSpecV3: OpenAPISpec = JSON.parse(readFileSync(specV3Path, 'utf-8'));
289 + v3Ops = getOperationsByTag(loadedSpecV3);
290 }
291
270 - // Collect tag descriptions from v3.1 spec
271 - const tagDescriptions: Record<string, string> = {};
292 + const v31TagDescriptions: Record<string, string> = {};
293 for (const tag of specV31.tags) {
273 - tagDescriptions[tag.name] = tag.description || '';
294 + v31TagDescriptions[tag.name] = tag.description || '';
295 }
275 -
296 const outputDir = join(process.cwd(), 'content/reference/api-reference');
297 const webhookSpec = loadWebhookSpec();
298
@@ -332,7 +352,7 @@ function generateIndexPages() {
352 continue;
353 }
354
335 - const tagDescription = tagDescriptions[tagName] || `${tagName} API endpoints`;
355 + const tagDescription = v31TagDescriptions[tagName] || `${tagName} API endpoints`;
356 // Display-title overrides for tags whose OpenAPI name is stale (e.g. the
357 // tool router is now Sessions). Keyed by slug.
358 const displayTitle = TITLE_OVERRIDES[tagSlug] ?? tagName;
@@ -377,7 +397,7 @@ ${body}
397
398 ## Endpoints
399
380 -<ApiEndpointsTable endpoints={${JSON.stringify(endpoints)}} />
400 +<ApiEndpointsTable endpoints={${serializeEndpoints(endpoints, `${tagSlug} (v3.1)`)}} />
401 `;
402
403 const folderPath = join(outputDir, tagSlug);
@@ -411,7 +431,7 @@ ${body}
431
432 ## Endpoints
433
414 -<ApiEndpointsTable endpoints={${JSON.stringify(v3Endpoints)}} />
434 +<ApiEndpointsTable endpoints={${serializeEndpoints(v3Endpoints, `${tagSlug} (v3.0)`)}} />
435 `;
436
437 const v3FolderPath = join(process.cwd(), 'content/reference/v3/api-reference', tagSlug);
docs/tests/integration/llm-endpoints.test.ts
+52
@@ -19,6 +19,58 @@ describe("LLM endpoints - llms.txt", () => {
19 });
20 });
21
22 +/**
23 + * Version labelling of the machine-readable indexes.
24 + *
25 + * `/reference/v3/` is the only version-shaped path in the corpus, so a search
26 + * for "composio api v3" matches the superseded tree exactly. Both index files
27 + * used to list the two trees interleaved under one unlabelled `## API
28 + * Reference` heading with no v3.1 string anywhere.
29 + */
30 +describe("LLM endpoints - API reference version labelling", () => {
31 + const CURRENT_HEADING = "## API Reference (v3.1, current)";
32 + const LEGACY_HEADING_PREFIX = "## API Reference (v3.0, legacy";
33 +
34 + test("/llms.txt labels the current reference group", async () => {
35 + const text = await (await fetchPage("/llms.txt")).text();
36 + expect(text).toContain(CURRENT_HEADING);
37 + });
38 +
39 + test("/llms.txt has no unlabelled API Reference heading", async () => {
40 + const text = await (await fetchPage("/llms.txt")).text();
41 + expect(text.split("\n")).not.toContain("## API Reference");
42 + });
43 +
44 + test("/llms.txt groups every legacy URL under the legacy heading, not interleaved", async () => {
45 + const lines = (await (await fetchPage("/llms.txt")).text()).split("\n");
46 +
47 + const legacyStart = lines.findIndex(line => line.startsWith(LEGACY_HEADING_PREFIX));
48 + expect(legacyStart, "no legacy reference group").toBeGreaterThan(-1);
49 +
50 + // The legacy group runs to the next ## heading.
51 + let legacyEnd = lines.findIndex(
52 + (line, i) => i > legacyStart && line.startsWith("## "),
53 + );
54 + if (legacyEnd === -1) legacyEnd = lines.length;
55 +
56 + const strays = lines
57 + .map((line, i) => ({ line, i }))
58 + .filter(
59 + ({ line, i }) =>
60 + line.includes("/reference/v3/") && (i < legacyStart || i >= legacyEnd),
61 + )
62 + .map(({ line }) => line);
63 +
64 + expect(strays, `legacy URLs outside the legacy group:\n${strays.join("\n")}`).toEqual([]);
65 + });
66 +
67 + test("/llms-full.txt carries no v3.0 page bodies", async () => {
68 + const text = await (await fetchPage("/llms-full.txt")).text();
69 + expect(text).not.toContain("/reference/v3/");
70 + expect(text).toContain("# Tools (/reference/api-reference/tools)");
71 + });
72 +});
73 +
74 describe("LLM endpoints - .md pages", () => {
75 const MD_PAGES = [
76 { path: "/docs/quickstart.md", name: "Quickstart" },
docs/tests/static/api-deprecation.test.tsx
+26 -1
@@ -29,7 +29,12 @@ interface SerializedEndpoint {
29
30 function createSpec(version: "v3.1" | "v3") {
31 return {
32 - tags: [{ name: "Tasks", description: "Task endpoints" }],
32 + tags: [
33 + {
34 + name: "Tasks",
35 + description: version === "v3.1" ? "Current task endpoints" : "Legacy task endpoints",
36 + },
37 + ],
38 paths: {
39 [`/${version}/tasks/deprecated`]: {
40 get: {
@@ -114,6 +119,11 @@ async function generateFixture(options?: { webhookSpec?: ReturnType<typeof creat
119 join(fixtureDir, "public/openapi-v3.json"),
120 JSON.stringify(createSpec("v3")),
121 );
122 + await mkdir(join(fixtureDir, "api-overviews"), { recursive: true });
123 + await writeFile(
124 + join(fixtureDir, "api-overviews/tasks.mdx"),
125 + "Current task overview with POST /api/v3.1/tasks/active",
126 + );
127 if (options?.webhookSpec) {
128 await writeFile(
129 join(fixtureDir, "public/openapi-webhooks.json"),
@@ -353,6 +363,21 @@ describe("deprecated API endpoints", () => {
363 }
364 });
365
366 + test("preserves the shared overview on current and legacy indexes", async () => {
367 + const fixtureDir = await generateFixture();
368 + const v31Content = await readFile(
369 + join(fixtureDir, "content/reference/api-reference/tasks/index.mdx"),
370 + "utf-8",
371 + );
372 + const v3Content = await readFile(
373 + join(fixtureDir, "content/reference/v3/api-reference/tasks/index.mdx"),
374 + "utf-8",
375 + );
376 +
377 + expect(v31Content).toContain("Current task overview with POST /api/v3.1/tasks/active");
378 + expect(v3Content).toContain("Current task overview with POST /api/v3.1/tasks/active");
379 + });
380 +
381 test("renders one Legacy badge for a deprecated endpoint and none for an active endpoint", () => {
382 const html = renderToStaticMarkup(
383 <ApiEndpointsTable
docs/tests/static/api-reference-routes.test.ts
+20 -3
@@ -23,8 +23,10 @@ import { readFileSync, readdirSync } from 'node:fs';
23 import { join, relative } from 'node:path';
24 import { loader, multiple } from 'fumadocs-core/source';
25 import { createOpenAPI, openapiSource } from 'fumadocs-openapi/server';
26 +import { z } from 'zod';
27
28 import { openapi, openapiV3 } from '../../lib/openapi';
29 +import { apiEndpointsSchema } from '../../lib/api-endpoints-table-schema';
30 import { HIDDEN_API_TAGS } from '../../lib/filter-api-version';
31
32 const DOCS_DIR = join(import.meta.dir, '../..');
@@ -235,7 +237,15 @@ describe('API reference quick links', () => {
237 return files;
238 }
239
238 - /** Parses the serialized endpoints of every ApiEndpointsTable in a file. */
240 + /**
241 + * Parses the serialized endpoints of every ApiEndpointsTable in a file.
242 + *
243 + * Validated through the same schema the runtime uses, not a bare
244 + * JSON.parse: `mdxToCleanMarkdown` degrades a malformed payload to an empty
245 + * table so one bad page cannot 500 the whole .md response, which means a
246 + * structurally broken committed payload would otherwise render nothing with
247 + * no failure signal anywhere. This is that signal.
248 + */
249 function parseEndpointHrefs(content: string, file: string): string[] {
250 const hrefs: string[] = [];
251 const prefix = /<ApiEndpointsTable endpoints=\{/g;
@@ -244,8 +254,15 @@ describe('API reference quick links', () => {
254 const start = match.index + match[0].length;
255 const end = content.indexOf('} />', start);
256 expect(end, `${file}: unterminated ApiEndpointsTable`).toBeGreaterThan(start);
247 - const endpoints: { href: string }[] = JSON.parse(content.slice(start, end));
248 - hrefs.push(...endpoints.map((endpoint) => endpoint.href));
257 + const parsed = apiEndpointsSchema.safeParse(JSON.parse(content.slice(start, end)));
258 + expect(
259 + parsed.success,
260 + `${file}: ApiEndpointsTable payload fails apiEndpointsSchema:\n${
261 + parsed.success ? '' : z.prettifyError(parsed.error)
262 + }`,
263 + ).toBe(true);
264 + if (!parsed.success) continue;
265 + hrefs.push(...parsed.data.map((endpoint) => endpoint.href));
266 }
267 // A file mentioning the component but yielding no parsed table means the
268 // generator's serialization drifted from this extractor — fail loudly
docs/tests/static/api-version-markdown.test.ts new
+336
@@ -0,0 +1,336 @@
1 +/**
2 + * API version identity in the markdown channels.
3 + *
4 + * Agents read `.md`, not the browser rendering path. Every signal that
5 + * separates v3.1 from v3.0 used to live in client components the markdown
6 + * converter dropped, so `reference.md` published an empty `Base URL` bullet
7 + * and the tag pages published an empty `Endpoints` section — while the
8 + * superseded v3.0 operation pages published a complete working curl example.
9 + *
10 + * These tests lock the three properties that fix costs the most to lose:
11 + * 1. `mdxToCleanMarkdown` renders `ApiBaseUrl` and `ApiEndpointsTable` at the
12 + * version the page URL implies, and degrades (no table, no throw) on a
13 + * malformed payload rather than 500ing the whole `.md` response.
14 + * 2. `getLLMText` emits a version pointer on `/reference/**` and nowhere else.
15 + * 3. The guidance text is single-sourced in `lib/api-version-guidance.ts` —
16 + * asserted by containment of the exported constant, not by matching a
17 + * copied literal, which is what proves the guardrail files compose rather
18 + * than restate.
19 + */
20 +import { describe, expect, test } from 'bun:test';
21 +
22 +import {
23 + REST_VERSION_GUIDANCE,
24 + TOOL_VERSION_GUIDANCE,
25 + TOOL_VERSION_PATHS,
26 + apiVersionPointer,
27 + isToolVersionPath,
28 +} from '../../lib/api-version-guidance';
29 +import { detectReferenceApiVersion, toCurrentVersionUrl } from '../../lib/api-version';
30 +import {
31 + getLLMText,
32 + getReferenceSource,
33 + mdxToCleanMarkdown,
34 + type LLMPage,
35 +} from '../../lib/source';
36 +import { DIRECT_EXECUTION_GUARDRAILS, SESSION_GUARDRAILS } from '../../lib/llm-guardrails';
37 +
38 +const V31_BASE = 'https://backend.composio.dev/api/v3.1';
39 +const V30_BASE = 'https://backend.composio.dev/api/v3';
40 +
41 +/** A current-tree tag page and its legacy twin. */
42 +const CURRENT_URL = '/reference/api-reference/tools';
43 +const LEGACY_URL = '/reference/v3/api-reference/tools';
44 +
45 +/** The authored MDX shape, which `lib/search-index.ts` reads from the file. */
46 +function endpointsTable(endpoints: unknown[]): string {
47 + return `## Endpoints\n\n<ApiEndpointsTable endpoints={${JSON.stringify(endpoints)}} />\n`;
48 +}
49 +
50 +/**
51 + * The shape `getLLMText` actually receives: fumadocs' processed markdown
52 + * re-serializes the JSX expression attribute as a quoted string with the inner
53 + * quotes entity-escaped. Matching only the authored shape above still passes a
54 + * unit test while leaving every live tag page's Endpoints section empty, which
55 + * is exactly the defect this work exists to fix — so the production shape gets
56 + * its own fixture.
57 + */
58 +function processedEndpointsTable(endpoints: unknown[]): string {
59 + const escaped = JSON.stringify(endpoints).replace(/"/g, '&#x22;');
60 + return `## Endpoints\n\n<ApiEndpointsTable endpoints="${escaped}" />\n`;
61 +}
62 +
63 +const TOOLS_ENDPOINT = {
64 + method: 'GET',
65 + pathV31: '/api/v3.1/tools',
66 + pathV3: '/api/v3/tools',
67 + summary: 'List tools',
68 + href: '/reference/api-reference/tools/getTools',
69 +};
70 +
71 +function llmPage(url: string, content: string, data: Partial<LLMPage['data']> = {}): LLMPage {
72 + return {
73 + url,
74 + data: { title: 'Tools', getText: async () => content, ...data },
75 + };
76 +}
77 +
78 +describe('mdxToCleanMarkdown — ApiBaseUrl', () => {
79 + test('renders the v3.1 base URL on a current-tree URL', () => {
80 + expect(mdxToCleanMarkdown('**Base URL**: <ApiBaseUrl />', CURRENT_URL)).toContain(V31_BASE);
81 + });
82 +
83 + test('renders the v3 base URL on a legacy-tree URL', () => {
84 + const markdown = mdxToCleanMarkdown('**Base URL**: <ApiBaseUrl />', LEGACY_URL);
85 + expect(markdown).toContain(`\`${V30_BASE}\``);
86 + expect(markdown).not.toContain(V31_BASE);
87 + });
88 +
89 + test('renders the v3.1 base URL with no url argument — the changelog call site', () => {
90 + expect(mdxToCleanMarkdown('**Base URL**: <ApiBaseUrl />')).toContain(V31_BASE);
91 + });
92 +});
93 +
94 +describe('mdxToCleanMarkdown — ApiEndpointsTable', () => {
95 + test('emits one row per endpoint using pathV31 on a current-tree URL', () => {
96 + const markdown = mdxToCleanMarkdown(
97 + endpointsTable([
98 + TOOLS_ENDPOINT,
99 + {
100 + method: 'POST',
101 + pathV31: '/api/v3.1/tools/execute/{tool_slug}',
102 + pathV3: '/api/v3/tools/execute/{tool_slug}',
103 + summary: 'Execute a tool',
104 + href: '/reference/api-reference/tools/executeTool',
105 + },
106 + ]),
107 + CURRENT_URL
108 + );
109 +
110 + expect(markdown).toContain('/api/v3.1/tools');
111 + expect(markdown).toContain('/api/v3.1/tools/execute/{tool_slug}');
112 + expect(markdown).not.toContain('/api/v3/tools');
113 + // href kept as a relative link, summary preserved
114 + expect(markdown).toContain('[List tools](/reference/api-reference/tools/getTools)');
115 + expect(markdown).toContain('[Execute a tool](/reference/api-reference/tools/executeTool)');
116 + });
117 +
118 + test('renders the processed-markdown shape getLLMText actually receives', () => {
119 + const markdown = mdxToCleanMarkdown(
120 + processedEndpointsTable([
121 + TOOLS_ENDPOINT,
122 + {
123 + method: 'GET',
124 + pathV31: '/api/v3.1/tools/{tool_slug}',
125 + pathV3: '/api/v3/tools/{tool_slug}',
126 + summary: 'Get tool by slug',
127 + href: '/reference/api-reference/tools/getToolsByToolSlug',
128 + },
129 + ]),
130 + CURRENT_URL
131 + );
132 +
133 + expect(markdown).toContain('[List tools](/reference/api-reference/tools/getTools)');
134 + expect(markdown).toContain('`/api/v3.1/tools/{tool_slug}`');
135 + // The escaping must actually be reversed, not carried through.
136 + expect(markdown).not.toContain('&#x22;');
137 + });
138 +
139 + test('uses pathV3 on a legacy-tree URL', () => {
140 + const markdown = mdxToCleanMarkdown(endpointsTable([TOOLS_ENDPOINT]), LEGACY_URL);
141 + expect(markdown).toContain('`/api/v3/tools`');
142 + expect(markdown).not.toContain('/api/v3.1/tools');
143 + });
144 +
145 + test('renders a visible legacy marker for a deprecated endpoint', () => {
146 + const markdown = mdxToCleanMarkdown(
147 + endpointsTable([{ ...TOOLS_ENDPOINT, legacy: true }]),
148 + CURRENT_URL
149 + );
150 + expect(markdown).toContain('Legacy');
151 + });
152 +
153 + test('preserves backslashes and pipes in endpoint summaries', () => {
154 + const markdown = mdxToCleanMarkdown(
155 + endpointsTable([{ ...TOOLS_ENDPOINT, summary: String.raw`Path \| pipe` }]),
156 + CURRENT_URL
157 + );
158 +
159 + expect(markdown).toContain(String.raw`[Path \\\| pipe]`);
160 + });
161 +
162 + test('emits no table and does not throw on a truncated payload', () => {
163 + const content = 'Surrounding prose.\n\n<ApiEndpointsTable endpoints={[{"method":"GET"} />\n';
164 + const markdown = mdxToCleanMarkdown(content, CURRENT_URL);
165 + // The rest of the page survives — one bad table must not take the whole
166 + // .md response down.
167 + expect(markdown).toContain('Surrounding prose.');
168 + expect(markdown).not.toContain('| Method |');
169 + });
170 +
171 + test('emits no table on a structurally invalid payload a bare JSON.parse would accept', () => {
172 + // Valid JSON, pathV31 missing.
173 + const markdown = mdxToCleanMarkdown(
174 + `Surrounding prose.\n\n${endpointsTable([
175 + { method: 'GET', pathV3: '/api/v3/tools', summary: 'List tools', href: '/x' },
176 + ])}`,
177 + CURRENT_URL
178 + );
179 + expect(markdown).toContain('Surrounding prose.');
180 + expect(markdown).not.toContain('| Method |');
181 + expect(markdown).not.toContain('List tools');
182 + });
183 +});
184 +
185 +describe('getLLMText — version pointer', () => {
186 + test('a current /reference/** page carries the v3.1 pointer and base URL', async () => {
187 + const text = await getLLMText(llmPage(CURRENT_URL, '# Tools'), { includeGuardrails: false });
188 + expect(text).toContain('**API version:**');
189 + expect(text).toContain(V31_BASE);
190 + });
191 +
192 + test('a legacy /reference/v3/** page carries the v3.0 pointer and links its v3.1 page', async () => {
193 + const text = await getLLMText(llmPage(LEGACY_URL, '# Tools'), { includeGuardrails: false });
194 + expect(text).toContain('**API version:**');
195 + expect(text).toContain('v3.0');
196 + expect(text).toContain(V31_BASE);
197 + expect(text).toContain('/reference/api-reference/tools.md');
198 + expect(text).not.toContain('https://docs.composio.dev/reference/api-reference/tools.md');
199 + });
200 +
201 + test('a /docs/** page gets no API version pointer — the pointer is reference-scoped', async () => {
202 + const text = await getLLMText(llmPage('/docs/quickstart', '# Quickstart'));
203 + expect(text).not.toContain('**API version:**');
204 + });
205 +
206 + test('an SDK reference page gets no REST version pointer', async () => {
207 + const text = await getLLMText(
208 + llmPage('/reference/sdk-reference/typescript/tools', '# Tools')
209 + );
210 + expect(text).not.toContain('**API version:**');
211 + });
212 +
213 + test('the glossary gets no REST version pointer', async () => {
214 + const text = await getLLMText(llmPage('/reference/glossary', '# Glossary'));
215 + expect(text).not.toContain('**API version:**');
216 + });
217 +
218 + test('the legacy authentication page links to its renamed current counterpart', async () => {
219 + const text = await getLLMText(
220 + llmPage('/reference/v3/authentication', '# Authentication'),
221 + { includeGuardrails: false }
222 + );
223 + expect(text).toContain('/reference/authenticating-to-composio.md');
224 + });
225 +
226 + test('every published legacy page links to an existing current-version page', async () => {
227 + const reference = await getReferenceSource();
228 + const routes = new Set(reference.getPages().map(page => page.url));
229 + const legacyRoutes = [...routes].filter(
230 + url => detectReferenceApiVersion(url) === '3.0'
231 + );
232 + const invalidPointers = legacyRoutes.flatMap(source => {
233 + const target = toCurrentVersionUrl(source);
234 + const pointer = apiVersionPointer(source);
235 + return routes.has(target) &&
236 + detectReferenceApiVersion(target) === '3.1' &&
237 + pointer.includes(`${target}.md`)
238 + ? []
239 + : [`${source} -> ${target}`];
240 + });
241 +
242 + expect(legacyRoutes.some(url => /^\/reference\/v3\/[^/]+$/.test(url))).toBe(true);
243 + expect(
244 + legacyRoutes.some(url => /^\/reference\/v3\/api-reference\/[^/]+$/.test(url))
245 + ).toBe(true);
246 + expect(
247 + legacyRoutes.some(url => /^\/reference\/v3\/api-reference\/[^/]+\/[^/]+$/.test(url))
248 + ).toBe(true);
249 + expect(
250 + invalidPointers,
251 + `invalid current-version pointers:\n${invalidPointers.join('\n')}`
252 + ).toEqual([]);
253 + });
254 +
255 + test('a legacy: true page keeps its legacy note and still emits no guardrails', async () => {
256 + const text = await getLLMText(
257 + llmPage('/docs/tools-direct/executing-tools', '# Executing tools', { legacy: true })
258 + );
259 + expect(text).toContain('**Legacy');
260 + // legacy: true gates the whole guardrail block at source.ts, before the
261 + // llmGuardrails selector ever runs. Deliberate: appending "enforce the
262 + // CURRENT patterns" to a point-in-time migration guide contradicts it.
263 + expect(text).not.toContain('Instructions for AI Code Generators');
264 + });
265 +});
266 +
267 +describe('detectReferenceApiVersion', () => {
268 + test.each([
269 + ['/reference/api-reference/tools', '3.1'],
270 + ['/reference/v3/api-reference/tools', '3.0'],
271 + ['/reference/glossary', null],
272 + ['/reference/sdk-reference', null],
273 + ['/reference/sdk-reference/typescript/tools', null],
274 + ] as const)('%s is classified as %s', (url, expected) => {
275 + expect(detectReferenceApiVersion(url)).toBe(expected);
276 + });
277 +});
278 +
279 +describe('guardrail sets compose the guidance rather than restating it', () => {
280 + // Containment of the exported constant, not a substring of prose. A test
281 + // matching a copied literal would pass just as happily against two strings
282 + // that currently agree and are free to drift.
283 + test.each([
284 + ['SESSION_GUARDRAILS', SESSION_GUARDRAILS],
285 + ['DIRECT_EXECUTION_GUARDRAILS', DIRECT_EXECUTION_GUARDRAILS],
286 + ])('%s contains both guidance constants verbatim', (_name, guardrails) => {
287 + expect(guardrails).toContain(REST_VERSION_GUIDANCE);
288 + expect(guardrails).toContain(TOOL_VERSION_GUIDANCE);
289 + });
290 +});
291 +
292 +describe('API version guidance constants', () => {
293 + test('the REST baseline names v3.1 without claiming route parity', () => {
294 + expect(REST_VERSION_GUIDANCE).toContain('https://backend.composio.dev/api/v3.1');
295 + expect(TOOL_VERSION_GUIDANCE).toContain(
296 + 'This version-default change is limited to the five endpoints above.'
297 + );
298 + expect(TOOL_VERSION_GUIDANCE).not.toMatch(/every non-tool endpoint.*unchanged/i);
299 + });
300 +
301 + test('exactly five tool paths need explicit version-default guidance', () => {
302 + expect(TOOL_VERSION_PATHS).toHaveLength(5);
303 + });
304 +});
305 +
306 +describe('isToolVersionPath normalization contract', () => {
307 + // Every key below appears verbatim in a committed spec. The predicate takes
308 + // the raw spec path key; no caller pre-strips anything.
309 + const cases: Array<[path: string, expected: boolean, why: string]> = [
310 + ['/api/v3.1/tools', true, ''],
311 + ['/api/v3.1/tools/{tool_slug}', true, 'fails if /api/v3 is stripped before /api/v3.1'],
312 + ['/api/v3.1/tools/execute/{tool_slug}', true, ''],
313 + ['/api/v3.1/tools/execute/{tool_slug}/input', true, ''],
314 + ['/api/v3.1/tools/scopes/required', true, 'v3.1-only; has no v3 counterpart'],
315 + ['/api/v3/tools', true, ''],
316 + ['/api/v3/tools/{tool_slug}', true, ''],
317 + ['/api/v3/tools/execute/{tool_slug}', true, ''],
318 + ['/api/v3/tools/execute/{tool_slug}/input', true, ''],
319 + ['/api/v3.1/tools/enum', false, 'under /tools, not affected — breaks a prefix match'],
320 + ['/api/v3.1/tools/execute/proxy', false, 'under /tools/execute, not affected'],
321 + [
322 + '/api/v3.1/tool_router/session/{session_id}/tools',
323 + false,
324 + 'ends in /tools — breaks a substring match',
325 + ],
326 + ['/api/v3.1/auth_configs', false, 'plain non-tool'],
327 + ['/api/v3.1/triggers_types', false, 'triggers already default to latest'],
328 + ['/tools/{tool_slug}', false, 'no version prefix; the predicate normalizes, it does not guess'],
329 + ];
330 +
331 + for (const [path, expected, why] of cases) {
332 + test(`${path} -> ${expected}${why ? ` (${why})` : ''}`, () => {
333 + expect(isToolVersionPath(path)).toBe(expected);
334 + });
335 + }
336 +});
docs/tests/static/content.test.ts
+21
@@ -114,6 +114,27 @@ describe("Content - provider compatibility", () => {
114 });
115 });
116
117 +describe("Content - Context7 ingest rules", () => {
118 + test("context7.json states the current REST version without claiming route parity", async () => {
119 + // Context7 ingests this repo for coding agents. Without a rule, nothing in
120 + // the ingested corpus says which REST version is current.
121 + const raw = await readFile(join(import.meta.dir, "../../../context7.json"), "utf-8");
122 + const rules: unknown = JSON.parse(raw).rules;
123 +
124 + expect(Array.isArray(rules)).toBe(true);
125 + expect((rules as unknown[]).length).toBeGreaterThan(0);
126 + expect(
127 + (rules as string[]).some(rule => rule.includes("https://backend.composio.dev/api/v3.1")),
128 + ).toBe(true);
129 + expect(
130 + (rules as string[]).some(rule =>
131 + rule.includes("This version-default change is limited to these five endpoints."),
132 + ),
133 + ).toBe(true);
134 + expect((rules as string[]).join("\n")).not.toMatch(/every non-tool endpoint.*unchanged/i);
135 + });
136 +});
137 +
138 describe("Content - changelog validation", () => {
139 test("changelog files use MM-DD-YY naming pattern", async () => {
140 let entries;
docs/tests/static/llms-openapi.test.ts
+233 -11
@@ -1,18 +1,13 @@
1 import { beforeAll, describe, expect, mock, test } from "bun:test";
2
3 +import {
4 + REST_VERSION_GUIDANCE,
5 + TOOL_VERSION_GUIDANCE,
6 +} from "../../lib/api-version-guidance";
7 +import { SESSION_GUARDRAILS } from "../../lib/llm-guardrails";
8 +
9 let bundledSpec: Record<string, unknown> = {};
10
5 -mock.module("@/lib/source", () => ({
6 - source: {},
7 - getReferenceSource: async () => ({}),
8 - examplesSource: {},
9 - toolkitsSource: {},
10 - changelogEntries: [],
11 - slugToDate: () => null,
12 - formatDate: () => "",
13 - getLLMText: async () => "",
14 - mdxToCleanMarkdown: async () => "",
15 -}));
11 mock.module("next/navigation", () => ({
12 notFound: () => {
13 throw new Error("not found");
@@ -28,6 +23,8 @@ mock.module("@/lib/meta-tools-data", () => ({
23 getMetaToolBySlug: async () => null,
24 }));
25 mock.module("@/lib/toolkit-schema", () => ({
26 + apiToolListSchema: { safeParse: (value: unknown) => ({ success: true, data: value }) },
27 + apiTriggerListSchema: { safeParse: (value: unknown) => ({ success: true, data: value }) },
28 processSchema: (schema: unknown) => schema,
29 toolFromApi: (tool: unknown) => tool,
30 }));
@@ -185,6 +182,231 @@ describe("LLM OpenAPI markdown", () => {
182 });
183 });
184
185 +/**
186 + * Version identity on operation pages.
187 + *
188 + * These are the pages that publish a complete working curl example, so they
189 + * are the strongest signal an agent acts on — and they never touch
190 + * mdxToCleanMarkdown, so a fix confined to lib/source.ts leaves them alone.
191 + *
192 + * Every fixture below uses production-shaped spec path keys — `/api/v3.1/…`
193 + * and `/api/v3/…`, with the `/api` segment — because that is what the
194 + * committed specs contain. The synthetic `/v3.1/test` keys in the fixtures
195 + * above predate this and are deliberately left alone; do not copy their shape
196 + * down here, or these tests will pass against an implementation that
197 + * mis-normalizes production paths.
198 + */
199 +describe("LLM OpenAPI markdown — API version identity", () => {
200 + function specWith(pathKey: string) {
201 + return {
202 + paths: {
203 + [pathKey]: {
204 + get: {
205 + summary: "Fixture operation",
206 + responses: { 200: { description: "Success" } },
207 + },
208 + },
209 + },
210 + servers: [{ url: "https://backend.composio.dev" }],
211 + };
212 + }
213 +
214 + function renderOperation(pageUrl: string, pathKey: string) {
215 + bundledSpec = specWith(pathKey);
216 + return openapiPageToMarkdown({
217 + url: pageUrl,
218 + data: {
219 + title: "Fixture operation",
220 + getOpenAPIPageProps: () => ({
221 + payload: { bundled: bundledSpec },
222 + operations: [{ path: pathKey, method: "GET" }],
223 + }),
224 + },
225 + });
226 + }
227 +
228 + const V31_PAGE = "/reference/api-reference/auth-configs/getAuthConfigs";
229 + const V30_PAGE = "/reference/v3/api-reference/auth-configs/getAuthConfigs";
230 +
231 + test("a v3.1 operation page carries the current-version pointer above the endpoint line", async () => {
232 + const markdown = await renderOperation(V31_PAGE, "/api/v3.1/auth_configs");
233 +
234 + expect(markdown).toContain("**API version:**");
235 + // Above **Endpoint:**, so a truncating reader still sees it.
236 + expect(markdown.indexOf("**API version:**")).toBeLessThan(
237 + markdown.indexOf("**Endpoint:**"),
238 + );
239 + });
240 +
241 + test("a v3.0 operation page carries the legacy pointer and links its v3.1 page", async () => {
242 + const markdown = await renderOperation(V30_PAGE, "/api/v3/auth_configs");
243 +
244 + expect(markdown).toContain("**API version:**");
245 + expect(markdown).toContain("v3.0");
246 + expect(markdown).toContain(
247 + "/reference/api-reference/auth-configs/getAuthConfigs.md",
248 + );
249 + expect(markdown.indexOf("**API version:**")).toBeLessThan(
250 + markdown.indexOf("**Endpoint:**"),
251 + );
252 + });
253 +
254 + test.each([
255 + ["v3.1", V31_PAGE, "/api/v3.1/tools/{tool_slug}"],
256 + ["v3.0", V30_PAGE, "/api/v3/tools/{tool_slug}"],
257 + ])(
258 + "a tool endpoint on %s carries both guidance constants exactly once",
259 + async (_label, pageUrl, pathKey) => {
260 + const markdown = await renderOperation(pageUrl, pathKey);
261 +
262 + // The v3.1 case fails if the predicate strips /v3.1 without /api, or
263 + // tries /api/v3 before /api/v3.1.
264 + expect(markdown.split(REST_VERSION_GUIDANCE)).toHaveLength(2);
265 + expect(markdown.split(TOOL_VERSION_GUIDANCE)).toHaveLength(2);
266 + },
267 + );
268 +
269 + test("renders both GET-by-slug version parameters with the v3.1 runtime default", async () => {
270 + const pathKey = "/api/v3.1/tools/{tool_slug}";
271 + bundledSpec = {
272 + paths: {
273 + [pathKey]: {
274 + get: {
275 + parameters: [
276 + { name: "version", in: "query", description: "Optional tool version" },
277 + {
278 + name: "toolkit_versions",
279 + in: "query",
280 + description: "Toolkit version specification",
281 + },
282 + ],
283 + responses: { 200: { description: "Success" } },
284 + },
285 + },
286 + },
287 + };
288 +
289 + const markdown = await openapiPageToMarkdown({
290 + url: "/reference/api-reference/tools/getToolsByToolSlug",
291 + data: {
292 + title: "Get tool",
293 + getOpenAPIPageProps: () => ({
294 + payload: { bundled: bundledSpec },
295 + operations: [{ path: pathKey, method: "GET" }],
296 + }),
297 + },
298 + });
299 +
300 + for (const parameter of ["version", "toolkit_versions"]) {
301 + const line = markdown
302 + .split("\n")
303 + .find(candidate => candidate.startsWith(`- \`${parameter}\``));
304 + expect(line).toContain("Defaults to `latest` when omitted on REST API v3.1.");
305 + }
306 + });
307 +
308 + test.each([
309 + [
310 + "v3.1 execute",
311 + "/reference/api-reference/tools/executeTool",
312 + "/api/v3.1/tools/execute/{tool_slug}",
313 + 'Tool version to execute (defaults to "00000000_00" if not specified)',
314 + "latest",
315 + "3.1",
316 + ],
317 + [
318 + "v3.1 scopes",
319 + "/reference/api-reference/tools/getRequiredScopes",
320 + "/api/v3.1/tools/scopes/required",
321 + "Toolkit version to resolve scopes against. Defaults to the pinned HTTP version when omitted.",
322 + "latest",
323 + "3.1",
324 + ],
325 + [
326 + "v3 input generation",
327 + "/reference/v3/api-reference/tools/generateToolInputs",
328 + "/api/v3/tools/execute/{tool_slug}/input",
329 + 'Tool version to use when generating inputs (defaults to "latest" if not specified)',
330 + "00000000_00",
331 + "3.0",
332 + ],
333 + ])(
334 + "replaces the stale %s request-body description",
335 + async (_label, pageUrl, pathKey, staleDescription, expectedDefault, apiVersion) => {
336 + bundledSpec = {
337 + paths: {
338 + [pathKey]: {
339 + post: {
340 + requestBody: {
341 + content: {
342 + "application/json": {
343 + schema: {
344 + type: "object",
345 + properties: {
346 + version: { type: "string", description: staleDescription },
347 + },
348 + },
349 + },
350 + },
351 + },
352 + responses: { 200: { description: "Success" } },
353 + },
354 + },
355 + },
356 + };
357 +
358 + const markdown = await openapiPageToMarkdown({
359 + url: pageUrl,
360 + data: {
361 + title: "Tool operation",
362 + getOpenAPIPageProps: () => ({
363 + payload: { bundled: bundledSpec },
364 + operations: [{ path: pathKey, method: "POST" }],
365 + }),
366 + },
367 + });
368 + const versionLine = markdown.split("\n").find(line => line.startsWith("- `version`"));
369 +
370 + expect(versionLine).toContain(
371 + `Defaults to \`${expectedDefault}\` when omitted on REST API v${apiVersion}.`
372 + );
373 + expect(versionLine).not.toContain(staleDescription);
374 + }
375 + );
376 +
377 + test("a non-tool endpoint carries the baseline and NOT the tool-version guidance", async () => {
378 + const markdown = await renderOperation(V31_PAGE, "/api/v3.1/auth_configs");
379 +
380 + expect(markdown).toContain(REST_VERSION_GUIDANCE);
381 + expect(markdown).not.toContain(TOOL_VERSION_GUIDANCE);
382 + });
383 +
384 + test("a near-miss endpoint under /tools behaves like a non-tool endpoint", async () => {
385 + // Under /tools, not one of the five — the case a prefix match gets wrong.
386 + const markdown = await renderOperation(
387 + "/reference/api-reference/tools/getToolsEnum",
388 + "/api/v3.1/tools/enum",
389 + );
390 +
391 + expect(markdown).toContain(REST_VERSION_GUIDANCE);
392 + expect(markdown).not.toContain(TOOL_VERSION_GUIDANCE);
393 + });
394 +
395 + test("neither page pulls in SESSION_GUARDRAILS", async () => {
396 + // SESSION_GUARDRAILS composes TOOL_VERSION_GUIDANCE. If an operation page
397 + // ever appended it, the tool-version text would arrive on every non-tool
398 + // page through the back door and the scoping above would be theatre.
399 + for (const [pageUrl, pathKey] of [
400 + [V31_PAGE, "/api/v3.1/auth_configs"],
401 + [V30_PAGE, "/api/v3/auth_configs"],
402 + ]) {
403 + const markdown = await renderOperation(pageUrl, pathKey);
404 + expect(markdown).not.toContain(SESSION_GUARDRAILS);
405 + expect(markdown).not.toContain("Instructions for AI Code Generators");
406 + }
407 + });
408 +});
409 +
410 describe("LLM page degradation", () => {
411 test("keeps a readable response when typed page parsing fails", () => {
412 expect(