Skip to content
atikulmunnaPublic

About

Turn an OpenAPI spec into a tested, human-approved, self-repairing TypeScript MCP server.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

unuMCP

Live demo: request access

Turn an OpenAPI specification into a working, tested TypeScript MCP server, with a human approval step, a deterministic code generator, a sandboxed test run, and a bounded self-repair loop.

You upload a spec; unuMCP analyses the endpoints, proposes tools (names, input schemas, risk levels), lets you approve them, generates a complete MCP server project, runs its tests in an isolated Docker sandbox, repairs failing code, and hands back a downloadable ZIP with the README and .env.example included, and no secrets.

unuMCP dashboard: the project build pipeline

The project workbench: a five-stage build pipeline (left), the validated spec with auto-detected bearer auth, and the approved tool plan whose descriptions were authored live by the LLM. Captured from a live AWS deploy (see Deployment).


Table of contents


Live demo

The demo runs on an on-demand cloud box that is kept switched off to keep hosting costs near zero, so there is deliberately no always-on public URL (see Deployment for why: it needs a real Docker daemon for the sandbox, which isn't free to run 24/7).

Want to see it live? Open the live-demo page (that's where the badge above goes), or reach out directly and the author will spin the server up (~30 seconds) and send you a URL, then take it down again afterwards:

In the meantime, the screenshot above and How it works walk through the entire pipeline.

How it works

The platform is a deterministic pipeline with one human gate, not an open-ended agent loop. Each stage advances a Project through an auditable state machine (every transition writes a GenerationRun status + an AuditEvent).

Upload OpenAPI spec
  → validate + dereference ($ref / allOf / oneOf)
  → analyse endpoints → propose tools (deterministic name + risk + input schema;
                                       optional LLM-authored descriptions, and an
                                       LLM risk rating that can only raise risk)
  → optional: agent usability check  (an LLM agent tries each tool; fixes to review)
  → 👤 human approval  (high-risk tools disabled by default)
  → generate TypeScript MCP server  (deterministic codegen, with a runtime
                                     safety policy: approval, dry run, read-only)
  → static security scan  (refuse code that smells of secrets / exfiltration / eval)
  → run tests in a locked-down Docker sandbox  (deps prebuilt into the image, test offline)
  → on failure: bounded self-repair loop  (fix implementation only, tests frozen)
  → complete → download ZIP  (sources + tests + README + .env.example, no secrets)

Design principles worth knowing before you read the code:

  • Determinism first. All structural artifacts (project scaffold, handler wiring, env detection, tests) are generated deterministically. The LLM is used only for prose (tool descriptions) and for repair edits, never to produce structural code. The platform runs end-to-end with the LLM disabled (you just get fallback descriptions and no repair).
  • The LLM is Claude, and opt-in. @unumcp/llm wraps Anthropic's official SDK (default Claude Haiku 4.5) behind a small LlmClient interface, so tests drive every LLM stage with a scripted client. It bills per token, so it runs only when explicitly turned on. Descriptions are proposed in batches (many tools per call) to keep the token cost of a large spec down. See Environment variables.
  • Generated tests check the contract, not just that code runs. Each tool is called through a real MCP client (in-memory transport) with the API stubbed, and its test asserts the exact HTTP request the spec defines: method, path, query (OpenAPI's default serialization), headers, auth, and body encoding. It also checks that the response reaches the agent unchanged, that API errors become tool errors, and that calls missing required inputs are rejected. The sandbox typechecks the server before running them. Injected bugs (wrong path, a dropped header or auth, a misencoded body, swallowed errors) all fail.
  • Tools are tested on an agent before you approve them. An on-demand check has an LLM play the agent: for up to 40 tools, most easily confused first, it gets a realistic request, written from the spec with each tool's real endpoint in view, and must pick the right tool, among the target and its closest look-alikes, with the right arguments. The agent sees only what an MCP client sees (names, descriptions, inputs). For each miss it proposes clearer tool text; when the agent picked the wrong tool, both tools of the confused pair are rewritten together, grounded in their endpoints and inputs. A fix is offered only if re-scoring shows it turns the miss into a hit without breaking another tool. You accept or reject each fix, and see the score before and after (for example 8 of 9, then 9 of 9) with the check's cost. Nothing generated is executed: the model only sees tool metadata. It needs the LLM; a 9-tool check costs about $0.03 on Claude Haiku 4.5, growing with the number of tools checked.
  • Large APIs stay reviewable. Tools are grouped by the spec's tags (GitHub's 1,209 tools fall into 47 groups). Long plans are shown by group, with a search and a switch per group; turning a group on leaves its high and critical tools off. The groups carry into the generated server as toolsets, so MCP_TOOLSETS=issues,pulls exposes just those groups at runtime.
  • A sample project shows the check without an API key. "Try a sample" on the projects page creates the Acme Billing sample: a small spec whose look-alike routes (all invoices with a status filter, and a separate drafts route) confuse an agent, the way many real specs do. Its usability check ran once with Claude and was recorded (apps/api/src/samples/acme-billing.recorded.ts), so creating a sample makes no LLM calls, while the rest of the pipeline runs live. After changing the sample spec or the check, refresh the recording with apps/api/scripts/record-sample.mts (its header explains how; it costs a few cents).
  • Risk is enforced at runtime, not just shown at approval. Risk comes from rules (method, sensitive nouns, and action words a method hides, such as merge or transfer); the LLM may rate a tool riskier, never safer, and a raise is audited. Every generated server carries the result: MCP behavior hints (readOnlyHint, destructiveHint, idempotentHint) on each tool, and a policy set by environment variables (MCP_READ_ONLY, MCP_TOOLSETS, MCP_ENABLED_TOOLS, MCP_DISABLED_TOOLS, MCP_DRY_RUN, MCP_CONFIRM_RISK). By default a high or critical tool runs only after the user approves the exact request through MCP elicitation; a client that can't ask gets a refusal, not a silent call. The generated tests prove each path (approve, decline, no elicitation support, dry run, read-only filtering), and removing any guard fails them.
  • Tests are frozen during repair. The repair loop may edit src/**/*.ts only: tests, package.json, and tsconfig.json are never offered to the model, and the parser rejects any other path. Every repair passes the same security scan as generated code before it is applied, and a run only counts as passing when at least one test reports a pass, so an edit can't win by making the suite run nothing.
  • Every internal LLM call is traced. Each agent tool call (propose_tool_descriptions_batch, repair_code) is recorded as an audit event with token counts, and its cost rolls up into per-run and platform metrics, with secrets redacted throughout.

Architecture

Layer Tech Notes
Language TypeScript 6 throughout The API and its packages compile ahead of time with SWC; dev runs from source
Backend / orchestrator NestJS 12 DI + guards map cleanly to the auth/authz and multi-stage layout
Frontend dashboard Next.js 16 (App Router), React 19, Tailwind v4 Same-origin /api/* proxied to the backend (no CORS needed)
Database PostgreSQL 16 via Prisma 7 (pg driver adapter) Projects, runs, tools, test results, repair attempts, audit log
Background jobs BullMQ + Redis (optional) Long-running generation/test/repair survive restarts; falls back to inline
Sandbox Docker, prebuilt image Dependencies baked into a content-hashed image; tests run with --network none, non-root, no capabilities, read-only mounts, resource caps
LLM Anthropic Claude (official SDK), via @unumcp/llm Opt-in (LLM_PROVIDER=anthropic); optional, since the platform degrades gracefully without it
Generated servers TypeScript 6, MCP SDK 1.32.1, Zod 4, Vitest 5 (Node 22.12+) One dependency set for every server, baked into the sandbox image
Testing Vitest 5, Playwright Unit and API suites against real Postgres, plus a browser smoke test of the production build in CI
Monorepo pnpm workspaces + Turborepo Shared packages/*, cached build/test/typecheck

Repository layout

apps/
  api/      NestJS backend: REST API + the pipeline orchestrator, jobs, sandbox, repair
  web/      Next.js dashboard: spec upload, tool approval, pipeline progress, downloads
packages/
  openapi/        Parse/validate OpenAPI, dereference $ref/allOf/oneOf, extract endpoints, detect auth
  analysis/       Endpoint → tool classification, deterministic naming, risk scoring, proposal assembly
  usability/      Agent usability check logic: look-alike selection, target picking, answer scoring
  schema-gen/     JSON Schema → Zod input-schema generation
  codegen/        Deterministic TypeScript MCP server generation (project, handlers, tests, README, .env.example)
  sandbox/        Docker sandbox: prebuilt dependency image, locked-down test runner, Vitest summary parser
  security-scan/  Secret redaction, static scan of generated code, prompt-injection detection
  llm/            Claude client (Anthropic SDK): tool descriptions, code repair, usability prompts
  db/             Prisma schema + generated client

Note on untracked docs: unuMCP_SRS.md, tasks.md, and CLAUDE.md are intentionally git-ignored (local planning/spec docs). This README is the canonical project documentation; ARCHITECTURE.md covers the design: pipeline, key decisions, trust boundaries, and what the requirement tags in code comments mean.

Prerequisites

  • Node.js ≥ 22.19 (required by swagger-parser 13, the spec dereferencer)
  • pnpm 11.5.1 (corepack enable will pin it from packageManager)
  • Docker: required both for local Postgres/Redis (docker compose) and for the test sandbox that runs a generated server's tests

Quick start

# 1. Install workspace deps (generates the Prisma client on postinstall)
pnpm install

# 2. Start Postgres (:5433) and Redis (:6379)
docker compose up -d

# 3. Configure env for the API
cp .env.example apps/api/.env
#   then edit apps/api/.env; at minimum set DATABASE_URL and JWT_SECRET
#   (REDIS_URL and the LLM, LLM_PROVIDER=anthropic plus ANTHROPIC_API_KEY, are optional; see below)

# 4. Apply the database schema.
#   The Prisma CLI reads DATABASE_URL from the environment (NOT apps/api/.env;
#   see packages/db/prisma.config.ts), so pass it for the docker-compose database:
DATABASE_URL=postgresql://unumcp:unumcp@localhost:5433/unumcp \
  pnpm --filter @unumcp/db exec prisma migrate deploy

# 5. Run the backend (http://localhost:3001/api)
pnpm --filter @unumcp/api dev

# 6. In another terminal, run the dashboard (http://localhost:3000)
pnpm --filter @unumcp/web dev

Open http://localhost:3000, register an account, create a project, and upload an OpenAPI spec to start the pipeline.

Environment variables

The API loads apps/api/.env (via Node's --env-file). Copy .env.example and adjust. All keys:

Variable Required Default Purpose
DATABASE_URL yes postgresql://unumcp:unumcp@localhost:5433/unumcp Postgres connection (Prisma)
JWT_SECRET yes none: the API refuses to start without it Signs/verifies auth tokens. At least 32 characters (openssl rand -hex 32)
PORT no 3001 API listen port
LLM_PROVIDER no (none) Set to anthropic to turn the LLM on; it also needs ANTHROPIC_API_KEY. A key alone never starts billing. Off ⇒ deterministic fallback, no repair
ANTHROPIC_API_KEY no (none) Anthropic key, used only with LLM_PROVIDER=anthropic
ANTHROPIC_MODEL no claude-haiku-4-5 Claude model id, e.g. claude-sonnet-5-5 or claude-opus-5-5. Cost appears in run metrics and /metrics
LLM_DISABLED no (none) Set true to force-disable the LLM even when configured
PROPOSAL_BATCH_SIZE no 5 Tools described per LLM call (batched proposal, P2-6)
PROPOSAL_CONCURRENCY no 3 Description batches in flight at once
USABILITY_MAX_TASKS no 40 Tasks per agent usability check (one per tested tool)
USABILITY_CONCURRENCY no 2 Agent calls in flight during a check
USABILITY_MAX_CALLS no 150 Hard ceiling on LLM calls per check; the run fails beyond it
REDIS_URL no (none) Absent ⇒ jobs run inline. Set to enable the durable BullMQ queue
JOBS_INLINE no (none) Set true to force inline execution even with REDIS_URL
JOB_ATTEMPTS no 3 BullMQ retry attempts per job
JOB_CONCURRENCY no 2 Worker concurrency
MAX_REPAIR_ATTEMPTS no 2 Bounded self-repair passes (each ≈ one LLM call + a full sandbox rerun)
REPAIR_MAX_TOKENS no 4096 Token ceiling per repair pass
SANDBOX_CONCURRENCY no 1 Sandbox runs (tests and repair reruns) allowed at once; further runs queue
RATE_LIMIT_MAX no 60 Requests per window
RATE_LIMIT_WINDOW_MS no 60000 Rate-limit window
RATE_LIMIT_DISABLED no (none) Set true to disable rate limiting
STORAGE_DIR no OS temp dir Where generated artifacts are stored locally

The web app honours API_URL (default http://localhost:3001) for the Next rewrite that proxies /api/* to the backend.

Secrets never leave the platform. Generated archives contain only .env.example placeholders, never a populated .env. Secret-shaped values are redacted from logs and error messages.

Running the apps

Backend. Start it with the workspace script:

pnpm --filter @unumcp/api dev                     # watch mode, straight from TypeScript
pnpm exec turbo run build --filter=@unumcp/api... # compile the API and its packages
pnpm --filter @unumcp/api start                   # run the compiled build (as production does)

⚠️ dev runs under node -r @swc-node/register, not tsx: NestJS needs emitDecoratorMetadata for constructor DI, and SWC emits it while esbuild/tsx does not. The build (scripts/swc-build.mjs) uses the same SWC transform, writing each package's dist/; start runs it with node -C unumcp-dist, the export condition that points the workspace packages at their dist/ instead of their TypeScript source.

Dashboard. Start the API first (it needs Postgres), then:

pnpm --filter @unumcp/web dev     # Next dev on :3000, proxies /api → :3001

The browser keeps the JWT in localStorage and calls same-origin /api/*; Next rewrites proxy those to the backend, so the API needs no CORS configuration.

Testing

pnpm test          # all packages via Turborepo
pnpm typecheck     # tsc --noEmit across the workspace
pnpm lint          # ESLint (typescript-eslint + React hooks) over the whole repo

Per package / app:

pnpm exec turbo run typecheck test --filter=@unumcp/llm
pnpm exec turbo run typecheck test build --filter=@unumcp/web

Notes:

  • The API test suite needs a Postgres with the schema applied (it exercises real Prisma against DATABASE_URL). Bring up docker compose and run prisma migrate deploy first.
  • Schema changes need a migration. After editing packages/db/prisma/schema.prisma, run pnpm --filter @unumcp/db exec prisma migrate dev --name <what-changed> and commit the new folder under prisma/migrations/. CI applies the migrations to an empty database and fails if the result differs from the schema.
  • The browser smoke test (pnpm --filter @unumcp/web e2e, Playwright, runs in CI) builds the web app for production, starts it and the API on ports 3100 and 3101, and drives Chromium through sign-up, a new project, a spec upload and a tool plan. It also checks the stylesheets and web fonts load. It needs the same Postgres; run pnpm --filter @unumcp/web exec playwright install chromium once.
  • The real-Redis queue round-trip test is opt-in: it only runs when REDIS_URL is set (the default suite runs jobs inline).
  • The real Docker sandbox is covered by an opt-in suite: RUN_SANDBOX_DOCKER_TESTS=1 pnpm --filter @unumcp/api exec vitest run tests/sandbox.security.e2e.test.ts proves, from inside a container, that there is no network, no root, and no write access to the project or the image, plus timeout cleanup and log redaction. Other unit/e2e tests use an injectable fake sandbox so they don't require Docker. The first real run builds the sandbox image (pnpm --filter @unumcp/sandbox build-image pre-builds it).

Observability

Two dependency-free surfaces (the JSON shapes are drop-in for a real shipper later):

  • Structured request logs + trace ids. One JSON line per HTTP request (requestId, method, path, status, durationMs); errors carry a correlationId that links the client envelope to the server log.
  • Metrics at GET /metrics (JWT-scoped to the caller): projects created, specs parsed, servers generated, generation success rate, test pass rate, average generation time, repair counts, failed sandbox runs, and LLM cost (totalInputTokens / totalOutputTokens / totalEstimatedCostUsd).
  • Per-call LLM trace (FR-031). Every internal agent tool call is an llm_tool_call audit event carrying an input/output summary, token counts, latency, and any error, all secret-redacted. Proposal and repair token usage rolls up onto the GenerationRun and into the metrics cost, priced per model from Claude's list prices.

Security posture

  • Human approval gate before any code is generated; high and critical tools (deletes, admin and auth endpoints, and irreversible actions like merge or transfer) are disabled by default.
  • Runtime approval in the generated server: risky calls wait for the user's approval through MCP elicitation, and the server can be limited to read-only tools, chosen toolsets, an allow list, or dry runs (see the generated README's "Safety controls").
  • Static security scan of generated code and of every LLM repair before it is persisted or packaged: refuses injected secrets, exfiltration hosts, and eval/shell patterns. Code is read through the TypeScript parser, so documentation (comments, tool and field descriptions) isn't mistaken for behaviour; that agent-facing text gets its own check: the API's own docs links pass, other links are noted for review, and an instruction to send data to an outside host is refused (tool poisoning).
  • Locked-down sandbox, no install step: every generated server declares the same dependency set, so it is baked into a prebuilt, content-hashed image and nothing is downloaded or installed at test time (a project declaring anything else is refused before any container starts). Tests run as the image's own Vitest (never a project npm script) with --network none, a non-root user, all capabilities dropped, no-new-privileges, CPU/memory/pid caps, a read-only root FS, and the project mounted read-only. Runs are serialized (SANDBOX_CONCURRENCY), and a timeout or cancel force-removes the container through the Docker daemon.
  • No default signing key: the API will not boot without a JWT_SECRET of at least 32 characters, and it signs and accepts HS256 tokens only.
  • Uploaded specs can't reach the server: a $ref to another file or a URL is refused at upload and never followed (it would make the server read its own files or fetch URLs), a server URL with spaces or line breaks is refused (it would add lines to the generated .env.example), and an upload's file name can't contain folders.
  • Prompt-injection detection on untrusted spec text feeding the LLM; the description prompt treats spec content as untrusted data.
  • Secret redaction across logs, error envelopes, and persisted sandbox output.
  • Sanitized error responses: a single exception filter returns a structured envelope with a correlation id; 5xx bodies are generic (details stay server-side).
  • Rate limiting on the API (per-client, per-endpoint windows). Behind the same-host Next.js proxy the client address comes from X-Forwarded-For, which is trusted only from a loopback peer, so clients get separate buckets and can't spoof their address by calling the API directly.

Deployment

The platform runs generated code in a Docker sandbox, so it needs a host with a real Docker daemon; managed PaaS free tiers that disallow Docker-in-Docker (Render/Railway) can't run the test stage. The included kit deploys the whole stack (API, web, Postgres, and the sandbox) onto one small AWS box, fully scripted and on-demand:

bash deploy/provision.sh        # launch + self-install an SSM-managed t4g.small (zero inbound ports)
bash deploy/manage.sh url       # print the free Cloudflare tunnel URL once it's up
bash deploy/manage.sh stop      # on-demand: stop when idle (billing drops to disk only)
bash deploy/manage.sh backups   # list the nightly database backups in S3
bash deploy/manage.sh teardown  # delete everything ($0)

Postgres runs in a container, jobs run inline (no Redis), and the public URL is a free *.trycloudflare.com quick tunnel (no Cloudflare account, no open ports). The schema is applied with migrations, the API runs as compiled JavaScript, and the database is backed up nightly to a private S3 bucket (kept 30 days; restoring is in the runbook). The LLM stays off on the demo: registration is open, so a paid key there could be spent by anyone. Secrets (JWT signing key, database password) are generated at launch and never committed. Full runbook, costs, and the stable-URL upgrade: deploy/DEPLOY.md.

Operational notes

  • Jobs are opt-in durable. With no REDIS_URL, generation/test/repair run inline in-request, which is fine for dev and CI. Set REDIS_URL to route them through BullMQ so they survive restarts. Either way, a boot-time reconciler settles anything a crash stranded: a generation run still running after 5 min fails, and a project stuck mid-test (then SANDBOX_FAILED, safe to retry) or mid-repair (then TESTS_FAILED) after 15 min is recovered with an audit event, so the pipeline never hangs.
  • The repair loop runs on the queue. A clean test failure triggers up to MAX_REPAIR_ATTEMPTS passes (LLM fix → sandbox rerun). Only a fix whose rerun passes is saved; on exhaustion the project settles on TESTS_FAILED (never a silent success) with the generated code unchanged, and every attempt stays in the repair history. The user may still download that partial output: any download with warnings (tests failed, errored, or never ran; auth to configure) embeds a WARNINGS.md saying so.
  • The LLM is Claude, opt-in. Set LLM_PROVIDER=anthropic and ANTHROPIC_API_KEY in apps/api/.env; ANTHROPIC_MODEL picks the model (default Claude Haiku 4.5). Every call's tokens and estimated cost appear in the audit trail and in /metrics.
  • Local storage for MVP. Artifacts are written under STORAGE_DIR (temp dir by default); the storage layer is abstracted so an object store can replace it without touching callers.

About

Turn an OpenAPI spec into a tested, human-approved, self-repairing TypeScript MCP server.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages