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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .github/actions/generate-mcp-tools/generate-tools.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { zodToJsonSchema } from "zod-to-json-schema";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, "../../..");
const README_PATH = path.join(ROOT, "README.md");
const TOOLS_DIR = path.join(ROOT, "src", "tools");

const START = "<!-- AUTO-GENERATED TOOLS START -->";
const END = "<!-- AUTO-GENERATED TOOLS END -->";

/**
* Load MCP tools
* Scans for any export that looks like an MCP tool:
* {
* name: string,
* description: string,
* parameters?: ZodSchema
* schema?: JSONSchema
* }
*/
async function loadTools() {
const files = fs
.readdirSync(TOOLS_DIR)
Comment on lines +25 to +26

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using fs.readdirSync performs synchronous I/O, which can block the Node.js event loop. For better performance and to avoid blocking, especially in a script that might run in a CI/CD environment, it's recommended to use the asynchronous fs.promises.readdir.

const files = (await fs.promises.readdir(TOOLS_DIR))
		.filter((f) => f.endsWith(".ts") && f !== "index.ts");

.filter((f) => f.endsWith(".ts") && f !== "index.ts");

const toolPromises = files.map(async (file) => {
const mod = await import(path.join(TOOLS_DIR, file));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When using dynamic import() with paths constructed via path.join, there can be issues with URL resolution in ESM contexts. It's generally safer and more robust to use new URL for dynamic imports to ensure correct resolution relative to the current module.

const mod = await import(new URL(path.join(TOOLS_DIR, file), import.meta.url).href);


const matches = Object.values(mod).filter(
(exp) =>
exp &&
typeof exp === "object" &&
typeof exp.name === "string" &&
typeof exp.description === "string" &&
(exp.parameters || exp.schema),
);

if (matches.length === 0) {
return null;
}

if (matches.length > 1) {
console.warn(
`Warning: ${file} exports multiple MCP-like tools. Using the first one.`,
);
}
Comment on lines +46 to +49

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current logic silently uses only the first MCP-like tool found if a file exports multiple. This could lead to unexpected behavior where other valid tools are ignored without explicit configuration or warning to the user that they are not being processed. Consider either processing all found tools or throwing an error if only one is expected, to prevent silent failures and make the script's behavior more predictable.


return matches[0];
});

const loadedTools = await Promise.all(toolPromises);
const tools = loadedTools.filter(Boolean);

return tools.sort((a, b) => a.name.localeCompare(b.name));
}

function renderSchema(schema) {
if (!schema) {
return "_No parameters_";
}

// If this is a Zod schema, convert it to JSON Schema
const jsonSchema =
typeof schema.safeParse === "function" ? zodToJsonSchema(schema) : schema;

const properties = jsonSchema.properties ?? {};
const required = new Set(jsonSchema.required ?? []);

if (Object.keys(properties).length === 0) {
return "_No parameters_";
}

// Check if any param has a default value to determine table columns
const hasDefaults = Object.values(properties).some(
(prop) => prop.default !== undefined,
);

// Build table header
let table = hasDefaults
? "| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n"
: "| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n";

// Build table rows
for (const [key, prop] of Object.entries(properties)) {
const type = Array.isArray(prop.type)
? prop.type.join(" | ")
: (prop.type ?? "unknown");

const requiredStr = required.has(key) ? "✅" : "";
const description = prop.description ?? "";
const defaultVal =
prop.default !== undefined ? JSON.stringify(prop.default) : "";

if (hasDefaults) {
table += `| \`${key}\` | ${type} | ${requiredStr} | ${defaultVal} | ${description} |\n`;
} else {
table += `| \`${key}\` | ${type} | ${requiredStr} | ${description} |\n`;
}
}

return table.trim();
}

function renderMarkdown(tools) {
let md = "";

for (const tool of tools) {
const schema = tool.parameters || tool.schema;

md += `### \`${tool.name}\`\n`;
md += `${tool.description}\n\n`;
md += `${renderSchema(schema)}\n\n`;
}

return md.trim();
}

function updateReadme({ readme, tools }) {
if (!readme.includes(START) || !readme.includes(END)) {
throw new Error("README missing AUTO-GENERATED TOOLS markers");
}

const toolsMd = renderMarkdown(tools);

return readme.replace(
new RegExp(`${START}[\\s\\S]*?${END}`, "m"),
`${START}\n\n${toolsMd}\n\n${END}`,
);
Comment on lines +128 to +131

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The replacement string adds \n\n before and after toolsMd. While this ensures spacing, if toolsMd itself already contains leading/trailing newlines (e.g., from renderMarkdown().trim() which might leave a trailing newline), it could result in excessive blank lines. It might be more consistent to ensure toolsMd is strictly trimmed of all leading/trailing whitespace and then explicitly add the desired number of newlines around it.

return readme.replace(
		new RegExp(`${START}[\s\S]*?${END}`, "m"),
		`${START}\n\n${toolsMd.trim()}\n\n${END}`,
	);

}

async function main() {
try {
const readme = fs.readFileSync(README_PATH, "utf8");
const tools = await loadTools();

if (tools.length === 0) {
console.warn("Warning: No tools found!");
}

const updated = updateReadme({ readme, tools });

fs.writeFileSync(README_PATH, updated);
console.log(`Synced ${tools.length} MCP tools to README.md`);
} catch (error) {
console.error("Error updating README:", error);
process.exit(1);
}
}

main().catch((err) => {
console.error(err);
process.exit(1);
});
47 changes: 47 additions & 0 deletions .github/workflows/sync-tools.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Sync MCP Tool Docs

on:
push:
branches:
- main

permissions:
contents: write

jobs:
sync-tools:
runs-on: ubuntu-latest

steps:
- name: Checkout repo
uses: actions/checkout@v4

- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20

- name: Install dependencies
run: |
if [ -f pnpm-lock.yaml ]; then
corepack enable
pnpm install --frozen-lockfile
else
npm install
fi

- name: Generate MCP tool documentation
run: npx tsx .github/actions/generate-mcp-tools/generate-tools.mjs

- name: Commit README changes
run: |
if git diff --quiet; then
echo "No README changes"
exit 0
fi

git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add README.md
git commit -m "chore: auto-sync MCP tool documentation"
git push
Loading