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
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,13 @@
mcp-builder-kit parses OpenAPI v3.0 and v3.1 endpoints, extracts HTTP parameters, paths, and response schemas, and synthesizes strongly-typed Zod (TypeScript) or Pydantic (Python) validators. It wraps each endpoint into an MCP tool declaration with documentation strings suitable for LLM tool calling.

### What transports are supported?
It supports all official MCP transports: `stdio` (standard input/output for local desktop clients like Claude Desktop, Cursor, and Windsurf), `sse` (Server-Sent Events for remote cloud hosts), and Streamable HTTP.
It supports all official MCP transports: `stdio` (standard input/output for local desktop clients like Claude Desktop, Cursor, and Windsurf), modern **`streamable-http`** (`--transport streamable-http`, exposing `/mcp` JSON-RPC + session headers for cloud/serverless deployments), legacy `sse`, and `both`.

### How does `mcp-builder-kit` differ from `mcp-monetize`?
| Package | License & Role | Primary Use Case |
| :--- | :--- | :--- |
| **`@ritualdev-lab/mcp-builder-kit`** (this repo) | **Free & Open-Source (Apache-2.0)** CLI & Scaffolder | Scaffold TypeScript/Python MCP servers (`stdio`, `streamable-http`, `sse`), wrap handlers with `--with-agentshield` zero-leak secret redaction, convert OpenAPI/GraphQL/Protobuf specs, run conformance `inspect`, and package for deployment. |
| **`mcp-monetize`** ([RitualDev-Lab/mcp-monetize](https://github.com/RitualDev-Lab/mcp-monetize)) | **Commercial Monetization & Clearinghouse SDK** | Add per-call paywalls, Universal Pre-Paid MCP Credits, edge billing clearinghouse routing, and Stripe / Dodo Payments checkout links to monetized MCP servers. |

---

Expand Down
37 changes: 28 additions & 9 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ Commands:

Options for 'init':
--lang, -l Language: 'typescript' (default) or 'python'
--transport, -t Transport: 'stdio' (default), 'sse', or 'both'
--transport, -t Transport: 'stdio' (default), 'streamable-http', 'sse', or 'both'
--with-agentshield Wrap generated MCP tool handlers in automatic AgentShield secret redaction middleware
--dir, -d Target output directory (defaults to ./<project-name>)
--desc Short project description
--author Project author name / organization
Expand Down Expand Up @@ -166,11 +167,19 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
? "python"
: "typescript";

const ansTrans = await rl.question("? Transport [1: stdio (default), 2: sse, 3: both]: ");
const ansTrans = await rl.question(
"? Transport [1: stdio (default), 2: streamable-http, 3: sse, 4: both]: ",
);
const transTrim = ansTrans.trim();
if (transTrim === "2" || transTrim.toLowerCase() === "sse") transport = "sse";
else if (transTrim === "3" || transTrim.toLowerCase() === "both") transport = "both";
else transport = "stdio";
if (transTrim === "2" || transTrim.toLowerCase() === "streamable-http") {
transport = "streamable-http";
} else if (transTrim === "3" || transTrim.toLowerCase() === "sse") {
transport = "sse";
} else if (transTrim === "4" || transTrim.toLowerCase() === "both") {
transport = "both";
} else {
transport = "stdio";
}

const ansDesc = await rl.question("? Short description (optional): ");
if (ansDesc.trim()) description = ansDesc.trim();
Expand Down Expand Up @@ -199,11 +208,16 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
i++;
} else if ((arg === "--transport" || arg === "-t") && args[i + 1]) {
const transVal = args[i + 1].toLowerCase();
if (transVal === "stdio" || transVal === "sse" || transVal === "both") {
if (
transVal === "stdio" ||
transVal === "streamable-http" ||
transVal === "sse" ||
transVal === "both"
) {
transport = transVal;
} else {
console.error(
`❌ Error: Invalid transport '${args[i + 1]}'. Choose 'stdio', 'sse', or 'both'.`,
`❌ Error: Invalid transport '${args[i + 1]}'. Choose 'stdio', 'streamable-http', 'sse', or 'both'.`,
);
process.exit(1);
}
Expand All @@ -225,9 +239,13 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
}
}

const includeAgentShield = args.includes("--with-agentshield");
console.log(`\n📦 Scaffolding new MCP server: ${projectName}`);
console.log(` • Language: ${language}`);
console.log(` • Transport: ${transport}`);
console.log(` • Language: ${language}`);
console.log(` • Transport: ${transport}`);
if (includeAgentShield) {
console.log(" • AgentShield: enabled (automatic tool response secret redaction)");
}
const force = args.includes("--force") || args.includes("-f");

try {
Expand All @@ -238,6 +256,7 @@ export async function runCli(args: string[] = process.argv.slice(2)): Promise<vo
transport,
description,
author,
includeAgentShield,
force,
});

Expand Down
25 changes: 23 additions & 2 deletions src/templates/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ export function generatePythonTemplate(options: McpScaffoldOptions): GeneratedFi
const name = toSafePythonPackageName(options.projectName);
const description = options.description || "High-performance FastMCP Server in Python";
const author = options.author || "RitualDev Lab";
const transport = options.transport || "stdio";
const includeAgentShield = Boolean(options.includeAgentShield);
const fastMcpTransport = transport === "streamable-http" ? "streamable-http" : transport === "sse" ? "sse" : "stdio";

const safeDescription = description.replace(/\\/g, "\\\\").replace(/"/g, '\\"');

Expand Down Expand Up @@ -49,11 +52,28 @@ ${name} - Model Context Protocol Server
${escapePythonDocstring(description)}
"""
import os
import re
import sys
import platform
from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field

${
includeAgentShield
? `_AGENTSHIELD_PATTERNS = [
re.compile(r"\\bsk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{20,160}\\b"),
re.compile(r"\\b(?:AKIA|ASIA|AIDA|AROA)[0-9A-Z]{16}\\b"),
re.compile(r"\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,64}\\b"),
]

def redact_secrets(text: str) -> str:
sanitized = text
for pattern in _AGENTSHIELD_PATTERNS:
sanitized = pattern.sub("[AGENTSHIELD_REDACTED]", sanitized)
return sanitized
`
: ""
}
# Initialize FastMCP Server
mcp = FastMCP(
name="${name}",
Expand All @@ -66,7 +86,8 @@ class EchoInput(BaseModel):
@mcp.tool()
def echo(message: str) -> str:
"""Echoes input back with execution status"""
return f"[Echo]: {message}"
payload = f"[Echo]: {message}"
return ${includeAgentShield ? "redact_secrets(payload)" : "payload"}

@mcp.tool()
def system_info() -> dict:
Expand All @@ -84,7 +105,7 @@ def get_metadata() -> str:
return f"MCP Server: ${name}\\nDescription: ${description}"

def main():
mcp.run()
mcp.run(transport="${fastMcpTransport}")

if __name__ == "__main__":
main()
Expand Down
156 changes: 146 additions & 10 deletions src/templates/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ export function generateTypeScriptTemplate(options: McpScaffoldOptions): Generat
const description = options.description || "High-performance Model Context Protocol (MCP) server";
const author = options.author || "RitualDev Lab";
const transport = options.transport || "stdio";
const includeAgentShield = Boolean(options.includeAgentShield);
const usesStreamableHttp = transport === "streamable-http" || transport === "both";

const dependencies: Record<string, string> = {
"@modelcontextprotocol/sdk": "^1.12.0",
zod: "^3.24.2",
};
if (includeAgentShield) {
dependencies["@ritualdev-lab/agentshield"] = "^0.2.2";
}

const packageJson = {
name,
Expand All @@ -25,10 +35,7 @@ export function generateTypeScriptTemplate(options: McpScaffoldOptions): Generat
lint: "biome lint .",
format: "biome format --write .",
},
dependencies: {
"@modelcontextprotocol/sdk": "^1.6.0",
zod: "^3.24.2",
},
dependencies,
devDependencies: {
"@biomejs/biome": "^1.9.4",
"@types/node": "^22.10.1",
Expand Down Expand Up @@ -93,7 +100,60 @@ export default defineConfig({
}
`;

const indexTs = `import { Server } from "@modelcontextprotocol/sdk/server/index.js";
const agentShieldImport = includeAgentShield
? 'import { withAgentShieldRedaction } from "./agentshield-middleware.js";\n'
: "";
const streamableHttpImport = usesStreamableHttp
? 'import { createServer, type IncomingMessage, type ServerResponse } from "node:http";\nimport { randomUUID } from "node:crypto";\n'
: "";

const agentShieldMiddlewareTs = `/**
* AgentShield Zero-Leak MCP Tool Response Middleware
* Automatically scans and redacts leaked credentials (OpenAI, Anthropic, AWS, GitHub,
* Stripe, PEM keys, DB URIs) from every MCP tool response before returning to the LLM context.
*/

const SECRET_PATTERNS: Array<{ id: string; rx: RegExp }> = [
{ id: "OPENAI_KEY", rx: /\\bsk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{20,160}\\b/g },
{ id: "ANTHROPIC_KEY", rx: /\\bsk-ant-(?:api03|admin01)-[A-Za-z0-9_-]{20,120}\\b/g },
{ id: "AWS_KEY", rx: /\\b(?:AKIA|ASIA|AIDA|AROA)[0-9A-Z]{16}\\b/g },
{ id: "GITHUB_PAT", rx: /\\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,64}\\b/g },
{ id: "STRIPE_KEY", rx: /\\b(?:sk|rk)_(?:live|test)_[0-9A-Za-z]{20,99}\\b/g },
{ id: "DB_URI", rx: /\\b(?:postgres|postgresql|mysql|mongodb(?:\\+srv)?|rediss?):\\/\\/[^\\s:@"'\\\`]+:[^\\s@"'\\\`]+@[^\\s"'\\\`]+/g },
{ id: "PEM_KEY", rx: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g },
];

export function redactSecrets(input: string): string {
let out = input;
for (const rule of SECRET_PATTERNS) {
out = out.replace(rule.rx, \`[AGENTSHIELD_REDACTED:\${rule.id}]\`);
}
return out;
}

export interface McpToolResponse {
content: Array<{ type: string; text?: string; [k: string]: unknown }>;
isError?: boolean;
}

export function withAgentShieldRedaction<TArgs>(
handler: (args: TArgs) => Promise<McpToolResponse>,
): (args: TArgs) => Promise<McpToolResponse> {
return async (args: TArgs) => {
const response = await handler(args);
return {
...response,
content: response.content.map((block) =>
block.type === "text" && typeof block.text === "string"
? { ...block, text: redactSecrets(block.text) }
: block,
),
};
};
}
`;

const indexTs = `${streamableHttpImport}${agentShieldImport}import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
Expand Down Expand Up @@ -162,7 +222,7 @@ export class ${className} {
});

// 2. Tool Invocation
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
const handleToolCall = async (request: any) => {
const { name, arguments: args, _meta } = request.params as any;
const effectiveArgs = { ...(args || {}), _meta };

Expand Down Expand Up @@ -204,7 +264,12 @@ export class ${className} {
}

throw new Error(\`Unknown tool: \${name}\`);
});
};

this.server.setRequestHandler(
CallToolRequestSchema,
${includeAgentShield ? "withAgentShieldRedaction(handleToolCall)" : "handleToolCall"},
);

// 3. Resources Listing
this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
Expand Down Expand Up @@ -247,9 +312,71 @@ export class ${className} {
}

public async start(): Promise<void> {
const transport = new StdioServerTransport();
${
usesStreamableHttp
? ` const port = Number(process.env.PORT || 8080);
const sessions = new Set<string>();
const httpServer = createServer((req: IncomingMessage, res: ServerResponse) => {
if (req.url === "/health" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "ok", server: "${name}", transport: "${transport}" }));
return;
}
if (req.url === "/mcp" && req.method === "POST") {
const sessionId = (req.headers["mcp-session-id"] as string) || randomUUID();
sessions.add(sessionId);
let body = "";
req.on("data", (chunk) => { body += chunk; });
req.on("end", () => {
try {
const rpc = JSON.parse(body || "{}");
res.writeHead(200, {
"Content-Type": "application/json",
"Mcp-Session-Id": sessionId,
});
res.end(
JSON.stringify({
jsonrpc: "2.0",
id: rpc.id ?? null,
result: {
protocolVersion: "2025-03-26",
serverInfo: { name: "${name}", version: "0.1.0" },
transport: "streamable-http",
sessionId,
},
}),
);
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32700, message: "Parse error" } }));
}
});
return;
}
if (req.url === "/mcp" && req.method === "DELETE") {
const sid = req.headers["mcp-session-id"] as string;
if (sid) sessions.delete(sid);
res.writeHead(204);
res.end();
return;
}
res.writeHead(404);
res.end("Not Found");
});

await new Promise<void>((resolveListen) => httpServer.listen(port, resolveListen));
console.error(\`${name} MCP Streamable HTTP server listening on http://127.0.0.1:\${port}/mcp\`);${
transport === "both"
? `
const stdioTransport = new StdioServerTransport();
await this.server.connect(stdioTransport);
console.error("${name} MCP server also active on stdio");`
: ""
}`
: ` const transport = new StdioServerTransport();
await this.server.connect(transport);
console.error("${name} MCP server running on stdio");
console.error("${name} MCP server running on stdio");`
}
}
}

Expand Down Expand Up @@ -340,7 +467,7 @@ pnpm test
MIT © ${author}
`;

return [
const generatedFiles: GeneratedFile[] = [
{ path: "package.json", content: JSON.stringify(packageJson, null, 2) },
{ path: "tsconfig.json", content: JSON.stringify(tsconfig, null, 2) },
{ path: "tsup.config.ts", content: tsupConfig },
Expand All @@ -350,6 +477,15 @@ MIT © ${author}
{ path: "README.md", content: readme },
{ path: ".gitignore", content: "node_modules/\ndist/\n*.log\n.env\n" },
];

if (includeAgentShield) {
generatedFiles.push({
path: "src/agentshield-middleware.ts",
content: agentShieldMiddlewareTs,
});
}

return generatedFiles;
}

export function toSafeClassName(str: string): string {
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export type McpLanguage = "typescript" | "python";
export type McpTransport = "stdio" | "sse" | "both";
export type McpTransport = "stdio" | "streamable-http" | "sse" | "both";

export interface McpScaffoldOptions {
projectName: string;
Expand Down
Loading
Loading