Skip to main content
Glama
Ni8crawler18

api2mcp-asp

by Ni8crawler18
README.md
# API2MCP — turn any OpenAPI spec into a paid MCP server

**OKX.AI Genesis Hackathon · Software Utility track**

API2MCP is an **Agentic Service Provider (ASP)**: give it any OpenAPI 3.x spec (JSON or YAML)
and it generates a complete, ready-to-deploy TypeScript **MCP server** scaffold — one MCP tool
per API operation, proxying the upstream API — with **x402 pay-per-call billing** already wired in.

It is deliberately meta: API2MCP is *itself* an MCP service that other agents pay (via x402) to
call, and each call mints *another* monetizable ASP for the OKX.AI marketplace. One paid service
that manufactures more paid services. See the ASP tutorial: <https://www.okx.ai/tutorial/asp>.

Generation is fully deterministic — plain template strings, no LLM calls.

## How it works

```
OpenAPI 3.x spec (JSON/YAML)
        |
        v
  API2MCP generator  ──────────────►  generated project (file map / zip)
   - parse + light validation           package.json, tsconfig.json
   - 1 operation -> 1 MCP tool          src/server.ts   (Express + MCP Streamable HTTP,
   - params/body -> Zod schemas                          fetch-proxy to the upstream API)
   - servers[0]  -> upstream base URL   src/x402.ts     (env-driven pay-per-call gate)
                                        README.md, .env.example, .gitignore
```

## Run it

```bash
npm install
npm run dev        # starts http://localhost:4402  (tsx watch)
# or: npm run build && npm start
npm test           # acceptance test: generated project must npm install + tsc cleanly
```

## Interfaces

### MCP (Streamable HTTP, stateless) — `POST /mcp`

| Tool | Pricing | Description |
| --- | --- | --- |
| `generate_mcp_server` | **paid** | `{openapi_spec, service_name?, price_usd?}` → `{files: {path: content}, tool_count, instructions}` |
| `preview_tools` | free | `{openapi_spec}` → list of `{name, description, params}` it would generate (teaser) |

```bash
curl -s http://localhost:4402/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
```

### REST

| Endpoint | Pricing | Returns |
| --- | --- | --- |
| `POST /api/generate` | paid | JSON `{service_name, tool_count, tools, files, instructions}` |
| `POST /api/generate.zip` | paid | zip archive of the generated project |
| `POST /api/preview` | free | tool listing teaser |

```bash
# Generate an MCP server from the bundled petstore fixture:
node -e 'console.log(JSON.stringify({openapi_spec: require("fs").readFileSync("examples/petstore.json","utf8"), price_usd: 0.01}))' \
  | curl -s http://localhost:4402/api/generate -H 'Content-Type: application/json' -d @- \
  | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const r=JSON.parse(s);console.log(r.service_name, r.tool_count, Object.keys(r.files));})'

# Or download it as a zip:
node -e 'console.log(JSON.stringify({openapi_spec: require("fs").readFileSync("examples/petstore.json","utf8")}))' \
  | curl -s http://localhost:4402/api/generate.zip -H 'Content-Type: application/json' -d @- -o petstore-mcp.zip
```

### CLI (local use, no server)

```bash
npx tsx src/cli.ts examples/petstore.json -o out/
cd out/petstore-mcp && npm install && npm run dev
```

## OKX payment

Paid calls are settled via OKX's official x402 seller middleware
(`@okxweb3/x402-express` + `@okxweb3/x402-core` + `@okxweb3/x402-evm`) against
the OKX facilitator on **X Layer** (`eip155:196`).

| Route                    | Price |
| ------------------------ | ----- |
| `POST /api/generate`     | $0.50 |
| `POST /api/generate.zip` | $0.50 |
| `POST /api/preview`      | $0.01 |

Env vars (all four OKX values plus `PAYMENT_ENABLED=true` are required to
activate payments; create keys at <https://web3.okx.com/onchainos/dev-portal>):

```bash
PAYMENT_ENABLED=true
OKX_API_KEY=...
OKX_SECRET_KEY=...
OKX_PASSPHRASE=...
PAY_TO_ADDRESS=0xYourWalletAddress
```

With payment active, unpaid requests to the paid routes get **HTTP 402** with an
`x402Version: 2` payment-required body listing the accepted `exact`-scheme
X Layer payment option. If any variable is missing, or OKX initialization
fails, the server logs one line and serves everything free — deploys stay safe
until real keys exist. `/healthz`, `/` and `/mcp` are never payment-gated.

Generated projects ship the same env-driven stub (`PAYMENT_ENABLED`, `PAY_TO_ADDRESS`,
`PRICE_USD`, `X402_NETWORK`) so every scaffold is monetizable out of the box.

## Acceptance test

`npm test` is the quality bar: it generates a project from `examples/petstore.json`
(5 operations: path params, query params, header param, enum, `$ref`/`allOf` schemas, POST/PUT
bodies), writes it to a temp dir, runs `npm install` and `npm run build` (tsc) inside it, and
fails unless the generated code compiles. Set `KEEP_GENERATED=1` to keep the temp project around.

## Layout

```
src/generator/   deterministic OpenAPI -> MCP project generator
  parse.ts         JSON/YAML parsing + light structural validation
  operations.ts    operation -> tool extraction (names, params, bodies)
  zod-codegen.ts   JSON Schema -> Zod source translation ($ref, enum, allOf/oneOf/anyOf)
  templates.ts     file templates for the generated project
src/server.ts    API2MCP service (MCP endpoint + REST + zip)
src/x402.ts      OKX x402 payment middleware (@okxweb3/x402-express, env-gated no-op by default)
src/cli.ts       local generation CLI
examples/        petstore fixture
test/validate.ts acceptance test (generated project must compile)
```