Skip to content
Draft
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
394 changes: 394 additions & 0 deletions GEMINI.md

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions commands/generator/generate.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
description = "Generate a minimal MCP server for selected Rocket.Chat APIs"
prompt = """
User's request: {{args}}

If the request is completely empty or has zero actionable detail (e.g. "make something"), ask what the MCP server should do.

Otherwise — even if the request is complex — ALWAYS run the full pipeline without stopping to ask:

1. `get_capability_guide` — match needs to operationIds.
2. `get_endpoint_schemas` — get exact field names for inputMapping.
3. `generate` — one call with the complete DSL. If it fails, retry the same payload.

Never stop to ask about implementation approach, limitations, or simplifications. If something can't be done exactly, approximate and generate anyway.

After `generate` succeeds, STOP. DO NOT read, edit, grep, or "fix" any files inside the generated project — even if the output mentions warnings, notes, or suggestions. Composer Notes are informational; they are already auto-resolved in the generated code. Confirm success and stop.
"""
14 changes: 14 additions & 0 deletions gemini-extension.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "mcp-server-generator",
"version": "0.1.0",
"owner": "sezallagwal",
"description": "Generate minimal MCP servers for Rocket.Chat APIs from a workflow DSL",
"contextFileName": "GEMINI.md",
"mcpServers": {
"mcp-server-generator": {
"command": "node",
"args": ["--import", "tsx", "${extensionPath}${/}src${/}index.ts"],
"cwd": "${extensionPath}"
}
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"type": "module",
"main": "dist/index.js",
"scripts": {
"build": "tsc -p tsconfig.build.json",
"build": "tsc -p tsconfig.build.json && node scripts/copy-engine-sources.mjs",
"check": "npm run format:check && npm run lint && npm run typecheck && npm run test && npm run build",
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
"dev": "tsx src/index.ts",
Expand Down
33 changes: 33 additions & 0 deletions scripts/copy-engine-sources.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Post-build step: copy the workflow engine `.ts` sources next to the compiled
* output in `dist/workflow/`.
*
* The generator vendors the engine into every generated project by reading its
* source files at runtime (see `src/generator/engine-bundle.ts`). `tsc` only
* emits `.js`, so without this copy a built/published `dist` package would have
* no engine sources to read. Copying the sources keeps the built package
* self-contained and identical in behavior to running from source.
*/
import { cpSync, existsSync, mkdirSync, readdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const repoRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
const srcWorkflow = join(repoRoot, "src", "workflow");
const distWorkflow = join(repoRoot, "dist", "workflow");

if (!existsSync(srcWorkflow)) {
console.error(`copy-engine-sources: missing source directory ${srcWorkflow}`);
process.exit(1);
}

mkdirSync(distWorkflow, { recursive: true });

const sources = readdirSync(srcWorkflow).filter((name) => name.endsWith(".ts"));
for (const name of sources) {
cpSync(join(srcWorkflow, name), join(distWorkflow, name));
}

console.error(
`copy-engine-sources: copied ${sources.length} engine source file(s) to dist/workflow`,
);
197 changes: 197 additions & 0 deletions src/generator/codegen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
import type { JSONSchema7 } from "json-schema";
import type { WorkflowDefinition } from "../workflow/types.js";
import type { GeneratorEndpoint } from "./types.js";
import { escapeBlockComment } from "./escape.js";

/** Indent a multi-line JSON blob so it nests cleanly inside generated source. */
function indentJson(value: unknown, indent = "const "): string {
void indent;
return JSON.stringify(value, null, 2)
.split("\n")
.map((line, i) => (i === 0 ? line : " " + line))
.join("\n");
}

/** Map a JSON-schema param entry to a Zod expression usable under Zod 3 and 4. */
function zodForParam(schema: JSONSchema7 | undefined): string {
const type =
typeof schema?.type === "string" ? schema.type.toLowerCase() : "";
switch (type) {
case "string":
return "z.string()";
case "number":
case "integer":
return "z.number()";
case "boolean":
return "z.boolean()";
case "array":
return "z.array(z.any())";
case "object":
return "z.record(z.string(), z.any())";
default:
return "z.any()";
}
}

function zodShape(params: JSONSchema7): string {
const props =
(params.properties as Record<string, JSONSchema7> | undefined) ?? {};
const required = new Set(
Array.isArray(params.required) ? params.required : [],
);
const entries = Object.entries(props).map(([key, schema]) => {
const base = zodForParam(schema);
const desc = schema?.description
? `.describe(${JSON.stringify(schema.description)})`
: "";
const optional = required.has(key) ? "" : ".optional()";
return ` ${JSON.stringify(key)}: ${base}${desc}${optional}`;
});
return entries.length > 0 ? `{\n${entries.join(",\n")}\n }` : "{}";
}

/** Generate `src/tools/<name>.ts` — the workflow embedded as data + handler. */
export function generateToolFile(workflow: WorkflowDefinition): string {
return `/**
* Workflow tool: ${escapeBlockComment(workflow.name)}
* ${escapeBlockComment(workflow.description)}
*
* Steps: ${escapeBlockComment(workflow.steps.map((s) => s.id).join(" -> "))}
* Generated by mcp-server-generator.
*/
import { runWorkflow } from "../engine/index.js";
import type { WorkflowDefinition } from "../engine/types.js";
import type {
EndpointInfo,
WorkflowClient,
WorkflowServer,
} from "../engine/executor.js";

const workflow: WorkflowDefinition = ${indentJson(workflow)};

export const tool = {
name: ${JSON.stringify(workflow.name)},
description: ${JSON.stringify(workflow.description)},
};

export interface ToolContext {
client: WorkflowClient;
server: WorkflowServer;
endpoints: Record<string, EndpointInfo>;
}

export function createHandler(ctx: ToolContext) {
return async (args: Record<string, unknown>) => {
const result = await runWorkflow(workflow, args, ctx);
return {
content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }],
...(result.status === "error" ? { isError: true } : {}),
};
};
}
`;
}

/** Generate `src/endpoints.ts` — the operationId -> { method, path } registry. */
export function generateEndpointMap(endpoints: GeneratorEndpoint[]): string {
const entries = endpoints
.map(
(ep) =>
` ${JSON.stringify(ep.operationId)}: { method: ${JSON.stringify(
ep.method.toUpperCase(),
)}, path: ${JSON.stringify(ep.path)} },`,
)
.join("\n");
return `/**
* Endpoint registry — operationId -> HTTP method + path.
* Generated by mcp-server-generator.
*/
export const endpointMap: Record<string, { method: string; path: string }> = {
${entries}
};
`;
}

/** Generate `src/server.ts` — the entry point wiring tools to stdio transport. */
export function generateServerEntry(
serverName: string,
workflows: WorkflowDefinition[],
moduleNames: string[],
): string {
const toolImports = workflows
.map(
(_w, i) =>
`import { tool as wfTool${i}, createHandler as createHandler${i} } from "./tools/${moduleNames[i]}.js";`,
)
.join("\n");

const registrations = workflows
.map(
(w, i) =>
` server.registerTool(\n` +
` wfTool${i}.name,\n` +
` { description: wfTool${i}.description, inputSchema: ${zodShape(w.params)} },\n` +
` createHandler${i}({ client, server: workflowServer, endpoints: endpointMap }) as never,\n` +
` );`,
)
.join("\n");

return `#!/usr/bin/env node
/**
* ${escapeBlockComment(serverName)} — MCP server
* Generated by mcp-server-generator. ${workflows.length} workflow tool(s).
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { endpointMap } from "./endpoints.js";
import { client, initAuth } from "./rc-client.js";
import type { WorkflowServer } from "./engine/executor.js";
${toolImports}

/**
* Adapter exposing the connected MCP client's sampling and elicitation to the
* workflow engine. createMessage asks the client's LLM; elicitInput asks the user.
*/
function makeWorkflowServer(mcp: McpServer): WorkflowServer {
return {
async createMessage(message) {
const res = await mcp.server.createMessage({
messages: [
{ role: "user", content: { type: "text", text: message.prompt } },
],
...(message.systemPrompt ? { systemPrompt: message.systemPrompt } : {}),
maxTokens: message.maxTokens ?? 1024,
});
const text =
res.content && res.content.type === "text" ? res.content.text : "";
return { content: { type: "text", text } };
},
async elicitInput(params) {
const res = await mcp.server.elicitInput({
message: params.message,
requestedSchema: params.requestedSchema as never,
});
return { action: res.action, content: res.content };
},
};
}

const server = new McpServer({ name: ${JSON.stringify(serverName)}, version: "1.0.0" });
const workflowServer = makeWorkflowServer(server);

${registrations}

async function main() {
await initAuth();
const transport = new StdioServerTransport();
await server.connect(transport);
console.error(${JSON.stringify(serverName)} + " running — ${workflows.length} workflow tool(s)");
}

main().catch((err) => {
console.error("Fatal error:", err);
process.exit(1);
});
`;
}
73 changes: 73 additions & 0 deletions src/generator/dsl-mapping.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import type { JSONSchema7 } from "json-schema";
import type { DslStep, DslWorkflow } from "../dsl/types.js";
import type { ComposeStepInput, ComposeWorkflowInput } from "../composer/types.js";
import type { StepConfig } from "../workflow/types.js";

/**
* Bridge the flat DSL step shape produced by the parser into the discriminated
* `StepConfig` union the composer consumes. This is the seam between the DSL
* front end and the workflow model.
*/
function stepConfig(step: DslStep): StepConfig {
switch (step.type) {
case "api_call":
return {
type: "api_call",
operationId: step.operationId ?? "",
inputMapping: step.inputMapping ?? {},
...(step.outputPath !== undefined ? { outputPath: step.outputPath } : {}),
...(step.forEach !== undefined ? { forEach: step.forEach } : {}),
...(step.as !== undefined ? { as: step.as } : {}),
};
case "sampling":
return {
type: "sampling",
prompt: step.prompt ?? "",
...(step.content !== undefined ? { content: step.content } : {}),
...(step.systemPrompt !== undefined ? { systemPrompt: step.systemPrompt } : {}),
...(step.maxTokens !== undefined ? { maxTokens: step.maxTokens } : {}),
...(step.responseFormat !== undefined
? { responseFormat: step.responseFormat as "text" | "json" }
: {}),
};
case "elicitation":
return {
type: "elicitation",
message: step.message ?? "",
requestedSchema: (step.requestedSchema ?? { type: "object" }) as JSONSchema7,
...(step.onDecline !== undefined ? { onDecline: step.onDecline } : {}),
};
case "transform":
return { type: "transform", expression: step.expression ?? "" };
case "conditional":
return {
type: "conditional",
condition: step.condition ?? "",
thenStep: step.thenStep ?? "",
...(step.elseStep !== undefined ? { elseStep: step.elseStep } : {}),
};
default:
throw new Error(`Unknown DSL step type "${step.type}" in step "${step.id}".`);
}
}

function toStepInput(step: DslStep): ComposeStepInput {
return {
id: step.id,
label: step.label ?? step.id,
config: stepConfig(step),
...(step.dependsOn && step.dependsOn.length > 0 ? { dependsOn: step.dependsOn } : {}),
};
}

/** Convert a parsed DSL workflow into the composer's input shape. */
export function dslWorkflowToComposeInput(
workflow: DslWorkflow,
): ComposeWorkflowInput {
return {
name: workflow.name,
description: workflow.description,
params: (workflow.params ?? { type: "object", properties: {} }) as JSONSchema7,
steps: workflow.steps.map(toStepInput),
};
}
Loading