#
tokens: 1673/50000 5/5 files
lines: off (toggle) GitHub
raw markdown copy
# Directory Structure

```
├── .gitignore
├── LICENSE
├── package-lock.json
├── package.json
├── README.md
├── src
│   └── index.ts
└── tsconfig.json
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
node_modules/
build/
*.log
.env*
```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
# openapi-client-generator MCP Server

A Model Context Protocol server to generate API clients by using TypeScript.


<a href="https://glama.ai/mcp/servers/taqmq8493y">
  <img width="380" height="200" src="https://glama.ai/mcp/servers/taqmq8493y/badge" alt="OpenAPI Client Generator MCP server" />
</a>

## Features

### Resources
- Generates an axios based API client that can be used to interact with the API.
- It uses OpenAPI / Swagger specs to generate the client.

### Prompts
- `generate_client` - Generate a API client for specified OpenAPI specs.

## Development

Install dependencies:
```bash
npm install
```

Build the server:
```bash
npm run build
```

For development with auto-rebuild:
```bash
npm run watch
```

## Installation

To use with Claude Desktop, add the server config:

On MacOS: `~/Library/Application Support/Claude/claude_desktop_config.json`  
On Windows: `%APPDATA%/Claude/claude_desktop_config.json`

```json
{
  "mcpServers": {
    "openapi-client-generator": {
      "command": "node",
      "args": [
        "< PATH TO >/openapi-client-generator/build/index.js"
      ]
    }
  }
}
```

### Debugging

Since MCP servers communicate over stdio, debugging can be challenging. We recommend using the [MCP Inspector](https://github.com/modelcontextprotocol/inspector), which is available as a package script:

```bash
npm run inspector
```

The Inspector will provide a URL to access debugging tools in your browser.

## Contributing

Feel free to contribute to the project by opening issues or submitting pull requests. We welcome any improvements or new features that align with the project's goals.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

----

Built with [Cline](https://github.com/cline/cline)

```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "openapi-client-generator",
  "version": "0.1.1",
  "description": "A Model Context Protocol server to generate API clients by using TypeScript.",
  "private": true,
  "type": "module",
  "bin": {
    "openapi-client-generator": "./build/index.js"
  },
  "files": [
    "build"
  ],
  "scripts": {
    "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
    "prepare": "npm run build",
    "watch": "tsc --watch",
    "inspector": "npx @modelcontextprotocol/inspector build/index.js"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "0.6.0",
    "@types/node-fetch": "^2.6.12",
    "axios": "^1.7.9",
    "node-fetch": "^2.7.0",
    "openapi-typescript-codegen": "^0.29.0"
  },
  "devDependencies": {
    "@types/node": "^20.11.24",
    "typescript": "^5.3.3"
  }
}
```

--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------

```typescript
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ErrorCode,
  ListToolsRequestSchema,
  McpError,
} from "@modelcontextprotocol/sdk/types.js";
import { generate } from "openapi-typescript-codegen";
import fs from "fs/promises";

interface GenerateClientArgs {
  input: string;
  output: string;
  httpClient: "fetch" | "axios";
}

class OpenApiClientGenerator {
  private server: Server;

  constructor() {
    this.server = new Server(
      {
        name: "openapi-client-generator",
        version: "0.1.1",
      },
      {
        capabilities: {
          tools: {},
        },
      }
    );

    this.setupToolHandlers();

    this.server.onerror = (error) => console.error("[MCP Error]", error);
    process.on("SIGINT", async () => {
      await this.server.close();
      process.exit(0);
    });
  }

  private setupToolHandlers() {
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: "generate_client",
          description:
            "Generate TypeScript API client from OpenAPI specification",
          inputSchema: {
            type: "object",
            properties: {
              input: {
                type: "string",
                description: "URL or file path to OpenAPI specification",
              },
              output: {
                type: "string",
                description: "Output directory for generated client",
              },
              httpClient: {
                type: "string",
                enum: ["fetch", "axios"],
                description: "HTTP client to use (fetch or axios)",
              },
            },
            required: ["input", "output", "httpClient"],
            additionalProperties: false,
          },
        },
      ],
    }));

    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name !== "generate_client") {
        throw new McpError(
          ErrorCode.MethodNotFound,
          `Unknown tool: ${request.params.name}`
        );
      }

      const args = request.params.arguments as unknown as GenerateClientArgs;

      try {
        // Ensure output directory exists
        await fs.mkdir(args.output, { recursive: true });

        // Generate client
        await generate({
          input: args.input,
          output: args.output,
          httpClient: args.httpClient,
          useOptions: true,
          useUnionTypes: true,
          exportSchemas: true,
          exportServices: true,
          exportCore: true,
          indent: "2",
        });

        // Get list of generated files
        const files = await fs.readdir(args.output);

        return {
          content: [
            {
              type: "text",
              text: `Successfully generated TypeScript API client in ${
                args.output
              }\n\nGenerated files:\n${files.join("\n")}`,
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Error generating client: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
          isError: true,
        };
      }
    });
  }

  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
    console.error("OpenAPI Client Generator MCP server running on stdio");
  }
}

const server = new OpenApiClientGenerator();
server.run().catch(console.error);

```