---
title: MCP Generator
description: Automatically generate MCP server code from your existing API endpoints using CodeSpar's scanner and generator.
---

import { Callout } from "fumadocs-ui/components/callout";
import { Step, Steps } from "fumadocs-ui/components/steps";

# MCP Generator

The MCP Generator scans your existing API source code, discovers endpoints, and generates a fully functional MCP server with tool definitions — turning any REST API into tools your AI agent can call.

<Callout type="info">
The MCP Generator is part of **CodeSpar Enterprise**. Use it three ways: the no-code **dashboard wizard** (Develop › Generate), the library (`@codespar/mcp-generator`), or the [CLI](/docs/cli).
</Callout>

## Dashboard wizard (Develop › Generate)

The fastest path — no install, no code. Open **Develop › Generate** in the dashboard and run a four-step pipeline that ends with a server which is **routable, governed, and isolated to your project** — not just generated code on disk.

<Steps>
<Step>
### Source

Point at your API one of three ways:

- **Paste source** — drop Express / Fastify / Next.js route handlers for an instant scan.
- **OpenAPI 3.x** — paste the raw spec (JSON or YAML); no source access needed.
- **GitHub repo** — give `owner/repo` (plus a token for private repos); the picker fetches the files most likely to hold endpoints and scans them.
</Step>
<Step>
### Endpoints

Toggle which discovered endpoints to expose as tools.
</Step>
<Step>
### Generate

Review the generated `server.ts` and tool definitions; rename the server or regenerate.
</Step>
<Step>
### Onboard & activate

**Onboard** saves the server to your project. **Activate** (with your API's upstream base URL + auth) seeds it into the router as a project-scoped rail — so every agent call to it runs through the same policy engine, credential vault, and audit chain as Pix, NF-e, and the rest. Then connect credentials to go live.
</Step>
</Steps>

<Callout type="info">
The dashboard wizard is the only path that makes a generated server **routable** today. The library and CLI (below) emit standalone server code you host yourself.
</Callout>

## Quickstart (CLI)

Generate an MCP server from an existing API without writing any generator code:

```bash
# From your API's source tree
codespar mcp generate \
  --source ./src/api \
  --framework express \
  --out ./mcp-my-api

# Inspect the generated tools
codespar tools list --server ./mcp-my-api

# Run it locally and smoke-test
codespar mcp serve ./mcp-my-api --port 3333
```

The CLI wraps the scanner and generator APIs described below — pick it when you want a one-shot build, or use the library when you want to embed generation in your own build pipeline.

## How it works

<Steps>
<Step>
### Scan

The **API Scanner** parses your TypeScript/JavaScript source files and discovers API endpoints. It supports Express, Fastify, and Next.js API routes.

```typescript
import { APIScanner } from "@codespar/mcp-generator";

const scanner = new APIScanner();
const endpoints = await scanner.scan("./src/api");

// Discovers:
// - HTTP method (GET, POST, PUT, DELETE)
// - Path and path parameters
// - Query parameters
// - Request body fields
// - JSDoc descriptions
```
</Step>
<Step>
### Generate tools

The **Generator** converts discovered endpoints into MCP tool definitions with JSON Schema inputs, descriptions, and semantic names.

```typescript
import { MCPGenerator } from "@codespar/mcp-generator";

const generator = new MCPGenerator();
const tools = generator.generateTools(endpoints);

// Each tool gets:
// - A semantic name (GET /api/users/:id → GetUser)
// - A description from JSDoc or path inference
// - A JSON Schema input_schema from params/body
```
</Step>
<Step>
### Generate server

The generator produces a complete MCP server configuration with runnable code.

```typescript
const server = generator.generateServer(
  "my-api",
  "MCP server for My API",
  endpoints,
);

// Output:
// - server.config: MCP server metadata
// - server.tools: Array of tool definitions
// - server.code: Generated TypeScript code
```
</Step>
</Steps>

## Example

Given this Express API:

```typescript title="src/api/orders.ts"
/**
 * Create a new order
 */
app.post("/api/orders", async (req, res) => {
  const { customer_id, items, shipping_address } = req.body;
  // ...
});

/**
 * Get order by ID
 */
app.get("/api/orders/:id", async (req, res) => {
  // ...
});

/**
 * List orders with filters
 */
app.get("/api/orders", async (req, res) => {
  const { status, from, to, limit } = req.query;
  // ...
});
```

The generator produces:

```json title="Generated tools"
[
  {
    "name": "CreateOrder",
    "description": "Create a new order",
    "input_schema": {
      "type": "object",
      "properties": {
        "customer_id": { "type": "string" },
        "items": { "type": "array" },
        "shipping_address": { "type": "object" }
      },
      "required": ["customer_id", "items"]
    }
  },
  {
    "name": "GetOrder",
    "description": "Get order by ID",
    "input_schema": {
      "type": "object",
      "properties": {
        "id": { "type": "string", "description": "Order ID" }
      },
      "required": ["id"]
    }
  },
  {
    "name": "ListOrders",
    "description": "List orders with filters",
    "input_schema": {
      "type": "object",
      "properties": {
        "status": { "type": "string" },
        "from": { "type": "string" },
        "to": { "type": "string" },
        "limit": { "type": "number" }
      }
    }
  }
]
```

## Supported frameworks

| Framework | Scanner support |
|-----------|----------------|
| Express | Routes, Router, middleware |
| Fastify | Route handlers, schemas |
| Next.js | App Router (`route.ts`), Pages API (`pages/api`) |

## Naming conventions

The generator creates semantic tool names from HTTP method + path:

| Method | Path | Generated name |
|--------|------|----------------|
| `GET` | `/api/users` | `ListUsers` |
| `GET` | `/api/users/:id` | `GetUser` |
| `POST` | `/api/users` | `CreateUser` |
| `PUT` | `/api/users/:id` | `UpdateUser` |
| `DELETE` | `/api/users/:id` | `DeleteUser` |
| `POST` | `/api/orders/:id/refund` | `RefundOrder` |

## Output types

```typescript
interface DiscoveredEndpoint {
  method: string;        // HTTP method
  path: string;          // Route path
  handler: string;       // Handler function name
  params: string[];      // Path parameters
  queryParams: string[]; // Query parameters
  bodyFields: string[];  // Request body fields
  description?: string;  // JSDoc description
}

interface MCPToolDefinition {
  name: string;
  description: string;
  input_schema: Record<string, unknown>;
}

interface MCPServerConfig {
  name: string;
  description: string;
  tools: MCPToolDefinition[];
  endpoints: DiscoveredEndpoint[];
  code: string;           // Generated TypeScript
}
```

## Next steps

<NextStepsGrid items={[
  { label: "SERVERS", title: "Servers & Toolkits", description: "Browse the existing server catalog.", href: "/docs/servers" },
  { label: "CONCEPT", title: "Tools & Meta-Tools", description: "How tools work in CodeSpar end-to-end.", href: "/docs/concepts/tools" },
  { label: "REFERENCE", title: "Servers API", description: "HTTP API for querying the server catalog.", href: "/docs/api/servers" },
  { label: "BUILD", title: "Build Your Own Server", description: "Manual server authoring when the generator isn't enough.", href: "/docs/build-your-own" },
]} />
