X Openapi Flow Mcp

io.github.tiago-marquesPublished by GitHub account tiago-marquesv1.7.4Updated Oct 25, 2026

OpenAPI lifecycle guard and MCP sidecar for policy-driven API orchestration.

Overview

AI-generated overview

A local MCP sidecar for x-openapi-flow that gives an assistant a machine-readable contract of an OpenAPI API's lifecycle states, call order and decision rules.

What you can do
Expose a dense, non-prose flow contract for coding agents so they know the exact call order, decision rules and field references for an integration, instead of re-deriving them from human documentation (export-llm-flows, callable as an MCP tool).
When to use it
Use it when an assistant such as a coding agent needs to implement or call a multi-step, stateful API correctly and should follow declared lifecycle transitions rather than guess the order of operations.
Requirements
Runs as a local stdio process on the desktop, installed from the npm package x-openapi-flow; Node.js and npx are needed. It works against an OpenAPI spec, typically with a generated openapi.x.json sidecar file. No authentication, environment variables or headers are declared.
Before you install
The README describes CLI commands that write and modify files in your project, such as init, apply and generated SDK, docs and test output; review changes before committing. The flow contract is derived from your OpenAPI spec, so keep that spec free of anything you would not want an agent to read.

Installation

In SourceWeft

  1. Open X Openapi Flow Mcp in the dashboard and add it to a workspace.
  2. Enable the server for the chats that should use its tools.

Desktop only via STDIO. STDIO servers start a local process, so they need the SourceWeft desktop host.

Other MCP clients

Follow the launch instructions in the repository.

README

OpenAPI describes APIs. x-openapi-flow turns them into executable workflows — for developers and AI agents.

Define your API workflows in openapi.x.json and execute them without writing custom clients or orchestration logic

[x-openapi-flow logo]

[npm version] [npm downloads] [npm total downloads] [node] [license] [CI] [open issues] [last commit] [copilot ready]

🚀 2,100+ downloads in the first 3 weeks!

⚡ Get started in seconds

npx x-openapi-flow init --suggest-transitions

This generates an openapi.x.json file where you can declaratively define how your API should be executed — not just described.

See your API lifecycle come alive from your OpenAPI spec, with one simple command

Validate, document, and generate flow-aware SDKs automatically.

[x-openapi-flow in action]

What is this?

x-openapi-flow extends your OpenAPI specification with a workflow layer.

openapi.json → describes your API
openapi.x.json → describes how to use it (flows)

Instead of writing imperative code to orchestrate API calls, you define workflows declaratively and run them anywhere.

x-openapi-flow adds a declarative state machine to your OpenAPI spec.

Model resource lifecycles, enforce valid transitions, and generate flow-aware artifacts for documentation, SDKs, and automation.

🚀 Example

Define stateful workflows and lifecycle transitions directly inside your OpenAPI operations:

json
{  "operationId": "createOrder",  "x-openapi-flow": {    "version": "1.0",    "id": "create-order",    "current_state": "created",    "description": "Creates an order and starts the lifecycle",    "transitions": [      {        "transition_id": "order-created-to-paid",        "trigger_type": "synchronous",        "condition": "Payment is confirmed",        "decision_rule": "payOrder:response.200.body.payment_status == 'approved'",        "target_state": "paid",        "next_operation_id": "payOrder",        "operation_role": "mutate",        "prerequisite_operation_ids": ["createOrder"],        "evidence_refs": [          "payOrder:response.200.body.payment_status"        ],        "propagated_field_refs": [          "createOrder:response.201.body.order_id"        ],        "failure_paths": [          {            "reason": "Payment denied",            "target_state": "payment_failed",            "next_operation_id": "getOrder"          }        ]      }    ]  }}

This flow defines an order lifecycle directly inside your OpenAPI:

  • Starts in the created state
  • Transitions to paid when payment is confirmed
  • Supports both synchronous and polling-based transitions
  • Propagates data between operations automatically
  • Can include explicit decision/evidence and failure-path metadata for AI-guided orchestration

Instead of manually orchestrating API calls, the workflow is fully described alongside your API specification.

Why This Exists

Building APIs is cheap. Building complex, multi-step APIs that teams actually use correctly is hard.

Teams face recurring problems:

  • 📄 Manual documentation is brittle – OpenAPI specs are static, often out of sync with real workflows
  • 🤖 AI agents can hallucinate – LLMs and code-generating agents may produce invalid calls if workflows are unclear or undocumented
  • 🤯 Workflows are confusing – multi-step operations are hard to track for humans and AI agents
  • ⚠️ Invalid calls slip through – developers make mistakes because lifecycle rules aren’t enforced
  • ⏱️ Integration slows down – SDKs, Postman collections, and docs need constant manual updates
  • 🛡️ Hard to prevent errors in production – without explicit lifecycle rules, invalid operations can reach live systems, causing outages or inconsistencies

x-openapi-flow exists to solve these pains: it makes lifecycles explicit, validates transitions automatically, and generates flow-aware docs and SDKs — so teams move faster, make fewer mistakes, and ship confident integrations.

What This Enables

Turn your OpenAPI spec into a single source of truth for API behavior:

Quick Start (without OpenAPI file)

Start in 2 Minutes (Online Playground)

Prefer no local setup? Open the minimal runtime-guard demo directly in your browser:

Once open, run:

bash
npm installnpm run start

Then in another terminal:

bash
curl -s -X POST http://localhost:3110/orderscurl -i -X POST http://localhost:3110/orders/<id>/ship

Expected: 409 INVALID_STATE_TRANSITION.

Fastest way to see value (guided scaffold):

bash
npx x-openapi-flow quickstartcd x-openapi-flow-quickstartnpm installnpm start

Optional runtime:

bash
npx x-openapi-flow quickstart --runtime fastify

Then run:

bash
curl -s -X POST http://localhost:3110/orderscurl -i -X POST http://localhost:3110/orders/<id>/ship

Expected: 409 INVALID_STATE_TRANSITION.


If you already have an OpenAPI file, use the sidecar workflow:

Initialize flow support in your project:

bash
npx x-openapi-flow init# optional: infer suggested transitions using naming heuristicsnpx x-openapi-flow init --suggest-transitions

After regenerating your OpenAPI file, apply and validate the flow (optional):

bash
npx x-openapi-flow apply openapi.yaml --out openapi.flow.yaml
npx x-openapi-flow validate openapi.flow.yaml --profile strict --strict-quality

This will:

  • enrich your OpenAPI spec with flow metadata
  • validate lifecycle consistency
  • catch invalid transitions early

💡 Tip: run this in CI to enforce API workflow correctness

Less Verbose DSL for Large Flows

For larger APIs, you can define flow rules by resource (with shared transitions/defaults) and reduce duplication in sidecar files.

See: Sidecar Contract

GitHub Action (One-Step CI Validation)

Use the official reusable action to validate lifecycle rules in CI with a single step:

yaml
- name: Validate OpenAPI flow rules  uses: tiago-marques/x-openapi-flow@v1  with:    openapi-file: openapi.flow.yaml    profile: strict    strict-quality: "true"

Integration guide: GitHub-Actions-Integration.md

Real Lifecycle Example

Here’s a real-world payment lifecycle represented in x-openapi-flow:

CREATED -> AUTHORIZED -> CAPTURED -> REFUNDED

Generate a visual graph of the lifecycle:

bash
npx x-openapi-flow graph openapi.flow.yaml --format mermaid

Resulting diagram:

mermaid
graph TDCREATED --> AUTHORIZEDAUTHORIZED --> CAPTUREDCAPTURED --> REFUNDED

This visualization makes your API workflow explicit, easy to communicate, and ready for documentation or demos.

Generate Flow-Aware SDKs

Create a TypeScript or Python SDK that respects your API’s lifecycle and transition rules, following best practices seen in leading companies like Stripe and Adyen:

  • Orchestrator by model: each resource exposes methods that enforce valid transitions
  • Chainable API calls: perform sequences naturally and safely
bash
npx x-openapi-flow generate-sdk openapi.flow.yaml --lang typescript --output ./sdknpx x-openapi-flow generate-sdk openapi.flow.yaml --lang python --output ./sdk

Example usage (TypeScript):

ts
const payment = await sdk.payments.create({ amount: 1000 });await payment.authorize();await payment.capture();

Example usage (Python — zero-dependency, stdlib urllib-backed client, generated under ./sdk/src):

python
from src import FlowApiClientfrom src.http_client import UrllibHttpClient
client = FlowApiClient(UrllibHttpClient("https://api.example.com"))payment = client.payment.create({"body": {"amount": 1000}})payment = payment.authorize()payment = payment.capture()

This SDK guides developers through valid transition paths, following patterns used by market leaders to ensure safe and intuitive integrations.

Runtime Enforcement (Express + Fastify + Hono)

CI validation is important, but production safety needs request-time enforcement.

x-openapi-flow now includes an official runtime guard for Node.js that can block invalid state transitions during request handling.

  • Works with Express and Fastify
  • Resolves operations by operationId (when available) or by method + route
  • Reads current resource state using your own persistence callback
  • Blocks invalid transitions with explicit 409 error payloads

Install and use directly in your API server:

js
const {  createExpressFlowGuard,  createFastifyFlowGuard,  createHonoFlowGuard,} = require("x-openapi-flow/lib/runtime-guard");

Express example:

js
const express = require("express");const { createExpressFlowGuard } = require("x-openapi-flow/lib/runtime-guard");const openapi = require("./openapi.flow.json");
const app = express();
app.use(  createExpressFlowGuard({    openapi,    async getCurrentState({ resourceId }) {      if (!resourceId) return null;      return paymentStore.getState(resourceId); // your DB/service lookup    },    resolveResourceId: ({ params }) => params.id || null,  }));

Fastify example:

js
const fastify = require("fastify")();const { createFastifyFlowGuard } = require("x-openapi-flow/lib/runtime-guard");const openapi = require("./openapi.flow.json");
fastify.addHook(  "preHandler",  createFastifyFlowGuard({    openapi,    async getCurrentState({ resourceId }) {      if (!resourceId) return null;      return paymentStore.getState(resourceId);    },    resolveResourceId: ({ params }) => params.id || null,  }));

Hono example:

js
const { Hono } = require("hono");const { createHonoFlowGuard } = require("x-openapi-flow/lib/runtime-guard");const openapi = require("./openapi.flow.json");
const app = new Hono();
app.use(  "*",  createHonoFlowGuard({    openapi,    async getCurrentState({ resourceId }) {      if (!resourceId) return null;      return paymentStore.getState(resourceId);    },    resolveResourceId: ({ params }) => params.id || null,  }));

Error payload for blocked transition:

json
{  "error": {    "code": "INVALID_STATE_TRANSITION",    "message": "Blocked invalid transition for operation 'capturePayment'. Current state 'CREATED' cannot transition to this operation.",    "operation_id": "capturePayment",    "current_state": "CREATED",    "allowed_from_states": ["AUTHORIZED"],    "resource_id": "pay_123"  }}

More details: Runtime Guard

Built-in Persistence Adapters

No need to write your own getCurrentState from scratch. x-openapi-flow ships five ready-made adapters:

js
const {  MemoryAdapter,   // in-process Map — ideal for tests and single-instance dev  FileAdapter,     // JSON file on disk — great for demos and local servers  RedisAdapter,    // ioredis-backed — production-ready, requires: npm install ioredis  GenericSQLAdapter, // any SQL DB (pg, mysql2, knex…) via query callback  MongoAdapter,    // MongoDB Collection-backed, requires: npm install mongodb} = require("x-openapi-flow/lib/runtime-guard");
// in-memory (testing / local)const store = new MemoryAdapter();app.use(createExpressFlowGuard({ openapi, ...store.forGuard() }));
// persist every transition to Redisconst Redis = require("ioredis");const redisStore = new RedisAdapter({ client: new Redis(), prefix: "orders:" });app.use(createExpressFlowGuard({ openapi, ...redisStore.forGuard() }));
// call setState after each successful request to keep the state in syncapp.post("/orders/:id/pay", async (req, res) => {  await redisStore.setState({ resourceId: req.params.id, state: "paid" });  res.json({ ok: true });});

GenericSQLAdapter example with pg:

js
const { Pool } = require("pg");const pool = new Pool();const sqlStore = new GenericSQLAdapter({  query: (sql, params) => pool.query(sql, params).then(r => r.rows),  dialect: "pg",});await sqlStore.ensureTable(); // CREATE TABLE IF NOT EXISTS xflow_state (…)app.use(createExpressFlowGuard({ openapi, ...sqlStore.forGuard() }));

MongoAdapter example with the official mongodb driver:

js
const { MongoClient } = require("mongodb");const client = await new MongoClient(process.env.MONGO_URL).connect();const mongoStore = new MongoAdapter({  collection: client.db("orders").collection("xflow_state"),});app.use(createExpressFlowGuard({ openapi, ...mongoStore.forGuard() }));

All adapters implement getCurrentState, setState, deleteState and forGuard() — a convenience method that returns the exact shape expected by the guard options.

Observability Hooks (Metrics/Audit)

You can instrument runtime decisions with onDecision to feed Prometheus, logs, or tracing.

js
const { Counter } = require("prom-client");const { createExpressFlowGuard } = require("x-openapi-flow/lib/runtime-guard");
const flowDecisions = new Counter({  name: "xflow_runtime_guard_decisions_total",  help: "Runtime guard decisions by type and operation",  labelNames: ["decision", "operation_id"],});
app.use(  createExpressFlowGuard({    openapi,    ...store.forGuard(),    onDecision(event) {      flowDecisions.inc({        decision: event.decision,        operation_id: event.operationId || "unknown",      });    },  }));

Common decision values include:

  • allowed_transition
  • allowed_idempotent_state
  • allowed_initial_state
  • denied_invalid_transition
  • denied_missing_resource_id
  • denied_unknown_operation
  • skipped_unknown_operation

Want to see the value immediately? Use the official minimal demo:

Run in under 5 minutes:

bash
cd example/runtime-guard/minimal-ordernpm installnpm start

Create an order, then try to ship before payment (must return 409 INVALID_STATE_TRANSITION):

bash
curl -s -X POST http://localhost:3110/orderscurl -i -X POST http://localhost:3110/orders/<id>/ship

HTTPie equivalent:

bash
http POST :3110/ordershttp -v POST :3110/orders/<id>/ship

Programmatic State Machine Engine

Use a reusable deterministic engine independently of CLI and OpenAPI parsing:

js
const { createStateMachineEngine } = require("x-openapi-flow/lib/state-machine-engine");
const engine = createStateMachineEngine({  transitions: [    { from: "CREATED", action: "confirm", to: "CONFIRMED" },    { from: "CONFIRMED", action: "ship", to: "SHIPPED" },  ],});
engine.canTransition("CREATED", "confirm");engine.getNextState("CREATED", "confirm");engine.validateFlow({ startState: "CREATED", actions: ["confirm", "ship"] });

More details: State Machine Engine

OpenAPI to Engine Adapter

Convert x-openapi-flow metadata to a pure engine definition:

js
const { createStateMachineAdapterModel } = require("x-openapi-flow/lib/openapi-state-machine-adapter");const { createStateMachineEngine } = require("x-openapi-flow/lib/state-machine-engine");
const model = createStateMachineAdapterModel({ openapiPath: "./openapi.flow.yaml" });const engine = createStateMachineEngine(model.definition);

More details: OpenAPI State Machine Adapter

Who Benefits Most

x-openapi-flow is ideal for teams and organizations that want clear, enforceable API workflows:

  • API-first organizations – maintain a single source of truth for API behavior
  • Teams building AI agents – provide AI-friendly contracts and enforce correct API usage, so agents can safely call endpoints in the right order without guessing or violating workflow rules
  • API platform teams – ensure consistent lifecycle rules across endpoints
  • Companies with complex API workflows – reduce errors and ambiguity in multi-step processes
  • SDK teams – generate flow-aware SDKs that guide developers

Why x-openapi-flow?

See how x-openapi-flow extends OpenAPI to make your API workflows explicit, enforceable, and actionable:

CapabilityOpenAPIx-openapi-flow
Endpoint contracts✅ Yes✅ Yes (fully compatible, extended)
Lifecycle states❌ No✅ Yes – define states for each resource
Transition validation❌ No✅ Yes – catch invalid calls before runtime
Flow diagrams❌ No✅ Yes – generate visual lifecycle graphs
Usage guidance (next valid actions)Limited/manual✅ Built-in via lifecycle metadata – guides developers and AI agents

How does it compare to OpenAPI Workflows (Arazzo) and AsyncAPI?

Dimensionx-openapi-flowOpenAPI Workflows (Arazzo)AsyncAPI
Primary focusResource lifecycle states & runtime enforcementMulti-step API workflows (orchestration scripts)Event-driven / async messaging APIs
Lifecycle states✅ Explicit states per resource❌ No state model❌ No state model
Runtime enforcement✅ Express/Fastify/Hono middleware (409 on invalid transitions)❌ Spec-only, no runtime guard❌ Spec-only
SDK generation✅ TypeScript, Python❌ No codegenLimited
Postman / Insomnia export✅ Built-in adapters❌ No❌ No
AI agent support✅ MCP sidecar + machine-oriented flow contract (export-llm-flows)❌ No❌ No
Breaking change detection✅ diff --breaking-only --fail-on-breaking❌ No❌ No
CI validation✅ CLI + GitHub Action❌ No official CLILimited
OpenAPI compatibility✅ Sidecar extends existing specsSeparate Arazzo specSeparate AsyncAPI spec

In short: use x-openapi-flow when you need enforceable, stateful API lifecycles that go beyond documentation into runtime safety, SDK generation, and AI-ready contracts. Use Arazzo for scripting multi-step HTTP journeys. Use AsyncAPI for documenting event/message-driven systems.

Integration Demos

Explore how x-openapi-flow integrates with popular API tools, making lifecycles and flows explicit for documentation and testing.

Swagger UI – Visualize Flows in Your Docs

bash
cd example/swagger-uinpm installnpm run applynpm start

[Swagger UI Flow Lifecycle 1]

Lifecycle panel shows valid states and transitions

[Swagger UI Flow Lifecycle 2]

Detailed view of transitions per operation

Redoc – Flow-Aware Documentation

bash
cd example/redocnpm installnpm run applynpm run generate

[Redoc Flow Lifecycle 1] [Redoc Flow Lifecycle 2] [Redoc Flow Lifecycle 3]

Auto-generated lifecycle diagrams make documentation clear and consistent

Postman – Organized API Collections

bash
cd example/postmannpm installnpm run applynpm run generate

[Postman Flow Lifecycle 1] [Postman Flow Lifecycle 2]

Collections reflect lifecycle order, reducing integration errors

Insomnia – Organized API Collections

bash
cd example/insomnianpm installnpm run applynpm run generate

[Insomnia Flow Lifecycle 1] [Insomnia Flow Lifecycle 2]

Requests are pre-organized according to lifecycle transitions

CLI Reference – Common Commands

Use x-openapi-flow from the command line to manage, validate, visualize, and generate SDKs/docs for your API workflows.

General

bash
npx x-openapi-flow help [command]         # show help for a specific command
npx x-openapi-flow --help                 # general help
npx x-openapi-flow version                # show version
npx x-openapi-flow doctor [--config path] # check setup and config
npx x-openapi-flow completion [bash|zsh]  # enable shell autocompletion
npx x-openapi-flow quickstart [--dir path] [--runtime express|fastify] [--force] # scaffold runnable onboarding project

Workflow Management

bash
# initialize flow supportnpx x-openapi-flow init [--flows path] [--force] [--dry-run]   
# apply flows to OpenAPInpx x-openapi-flow apply [openapi-file] [--flows path] [--out path]  
# validate transitionsnpx x-openapi-flow validate <openapi-file> [--profile core|relaxed|strict] [--strict-quality] [--semantic]  
# preview sidecar changesnpx x-openapi-flow diff [openapi-file] [--format pretty|json]
# detect breaking flow changes (use in CI to fail PRs)npx x-openapi-flow diff [openapi-file] --breaking-only --fail-on-breaking
# generate a Markdown migration guide for breaking flow changesnpx x-openapi-flow migrate [openapi-file] [--flows path] [--format markdown|json] [--out path]

Visualization & Documentation

bash
# generate lifecycle diagramsnpx x-openapi-flow graph [openapi-file] [--format mermaid|json]   
# generate Redoc docsnpx x-openapi-flow generate-redoc [openapi-file] [--output path]   
# export human-readable flow docs (Mermaid diagrams + prose)npx x-openapi-flow export-doc-flows [openapi-file] [--output path] [--format markdown|json]  
# export a machine-oriented flow contract for coding agents (not for humans)npx x-openapi-flow export-llm-flows [openapi-file] [--output path] [--format yaml|json]

SDK Generation

bash
# generate flow-aware SDK (typescript or python)npx x-openapi-flow generate-sdk [openapi-file] --lang typescript|python [--output path] 

Test Generation

bash
# generate executable flow tests (happy path + invalid transitions)npx x-openapi-flow generate-flow-tests [openapi-file] [--format jest|vitest|postman] [--output path]
# postman/newman-oriented collection with flow scriptsnpx x-openapi-flow generate-flow-tests [openapi-file] --format postman [--output path] [--with-scripts]

Full details:

NestJS Integration

Dedicated package: x-openapi-flow-nestjs-kit

bash
npm install x-openapi-flow x-openapi-flow-nestjs-kit

Then import from x-openapi-flow-nestjs-kit.

This package wraps the official runtime-guard helpers and exposes a NestJS-first API.

Release automation for this package uses dedicated tags in the format nestjs-v<version> (example: nestjs-v0.1.1) so it does not conflict with x-openapi-flow tags.

Option A: Middleware (drop-in)

ts
// flow-guard.middleware.tsimport { Injectable, NestMiddleware } from "@nestjs/common";import { createFlowMiddleware, MemoryAdapter } from "x-openapi-flow-nestjs-kit";import openapi from "./openapi.flow.json";
const store = new MemoryAdapter(); // swap for RedisAdapter or GenericSQLAdapter in productionconst guard = createFlowMiddleware({ openapi, ...store.forGuard() });
@Injectable()export class FlowGuardMiddleware implements NestMiddleware {  use(req: any, res: any, next: () => void) {    guard.use(req, res, next);  }}
// app.module.ts — apply to specific routesexport class AppModule implements NestModule {  configure(consumer: MiddlewareConsumer) {    consumer.apply(FlowGuardMiddleware).forRoutes("orders");  }}

Option B: CanActivate Guard

ts
// flow.guard.tsimport { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";import { createFlowGuard, MemoryAdapter } from "x-openapi-flow-nestjs-kit";import openapi from "./openapi.flow.json";
const store = new MemoryAdapter();const flowGuard = createFlowGuard({ openapi, ...store.forGuard() });
@Injectable()export class FlowGuard implements CanActivate {  canActivate(context: ExecutionContext) {    return flowGuard.canActivate(context);  }}

After each successful state-changing request, call store.setState to advance the resource:

ts
@Post(":id/pay")async pay(@Param("id") id: string) {  // … business logic …  await store.setState({ resourceId: id, state: "paid" });  return { ok: true };}

Documentation and Guides

Get the most out of x-openapi-flow with detailed guides, examples, and integration instructions:

Community and Proof

Roadmap

We’re actively expanding x-openapi-flow to support multiple platforms and SDKs. Check our progress:

  • 🗂 Roadmap Overview – #2
    See planned features and high-level goals

  • 🐍 Python SDK MVP – #3
    Enable Python developers to use flow-aware SDKs

  • 🏎 Go SDK MVP – #4
    Bring lifecycle-aware SDKs to Go projects

  • ☕ Kotlin SDK MVP – #5
    Support Android and JVM developers with flow-aware SDKs

Changelog

Keep track of updates and improvements in x-openapi-flow:

Documentation Language Policy

To ensure clarity and accessibility for the global developer community, all project documentation should be written in English. This helps contributors, users, and AI agents understand and use x-openapi-flow consistently.

Source: x-openapi-flow/README.md at commit 76bd26e

Tools

0
SourceWeft has not started this package in its sandbox yet, so its tools are not known.

Version history

1
  1. v1.7.4LatestSep 16, 2026

Score

50% of the applicable checks met

How complete this listing is, computed from the registry entry, the endpoint and public sources. Not a rating of the server and not a statement that it is safe or working today: reachability is a dated check, and no installs or reviews go into the score.

  • Reached in the last 30 days25 pts

    Keep the endpoint answering the MCP handshake; SourceWeft probes it every 30 days.

  • Auth declared10 pts

    Declare the credential headers in the registry entry, or keep the endpoint answering the probe so its auth can be classified.

  • Tools listed15 pts

    Answer tools/list without a credential, or ship a package that starts in a sandbox without one.

  • DescriptionRequired15 pts
  • Logo10 pts
  • Documentation15 pts
  • License10 pts