openapi-mcp-generator

repository·main·Indexed 20 days ago

https://github.com/harsha-iiiv/openapi-mcp-generator

A CLI and programmatic tool that converts OpenAPI 3.0+ specifications into Model Context Protocol (MCP) servers. It enables AI agents to interact with REST APIs via typed, validated servers supporting stdio, web (SSE), and streamable-http transport modes. Features include Zod validation schemas, support for multiple authentication schemes (API Key, Bearer, Basic, OAuth2), and the ability to filter endpoints using the x-mcp vendor extension.

Tokens
12.5K
Snippets
36
Records
51
Agent score
69%

What's inside openapi-mcp-generator

  1. How token caching works in the MCP server

    main

    When using the client credentials flow, the MCP server automatically manages token lifecycle through caching to minimize redundant authentication requests.

    Caching Logic:

    • Tokens are cached for their lifetime as defined by the expires_in parameter in the OAuth token response.
    • A 60-second safety margin is subtracted from the lifetime to prevent using an expired token.

    Request Workflow:

    1. The server checks for a valid, non-expired cached token.
    2. If a valid token exists, it is used for the API request.
    3. If no valid cached token is found, the server requests a new token before proceeding with the API call.
  2. Compare MCP Transport Modes

    main

    Choose a transport mode based on your deployment environment and client requirements:

    Featurestdioweb (SSE)streamable-http
    ProtocolJSON-RPC over stdioJSON-RPC over SSEJSON-RPC over HTTP
    ConnectionPersistentPersistentRequest/response
    BidirectionalYesYesYes (stateful)
    Multiple clientsNoYesYes
    Browser compatibleNoYesYes
    Firewall friendlyNoYesYes
    Load balancingNoLimitedYes
    Status codesNoLimitedFull HTTP codes
    HeadersNoLimitedFull HTTP headers
    Test clientNoYesYes
  3. How token caching works in the petstore-auth MCP server

    main

    When using the client credentials flow, the MCP server automatically manages token lifecycles to minimize redundant authentication requests.

    Caching Logic:

    • Tokens are cached for their lifetime as defined by the expires_in parameter in the OAuth response, minus a 60-second safety margin.
    • Request Workflow:
      1. The server checks for a valid cached token.
      2. If a valid token exists, it is used immediately.
      3. If no valid token is found (or if the token is within the 60-second expiration margin), the server requests a new token.
  4. Filter endpoints using the x-mcp extension

    main

    You can control which OpenAPI operations are exposed as MCP tools by using the x-mcp vendor extension. This extension can be applied at the root, path, or operation level.

    Precedence Rules:

    1. Operation level (highest)
    2. Path level
    3. Root level (lowest)

    Usage:

    • x-mcp: true (or the string "true") includes the endpoint.
    • x-mcp: false (or the string "false") excludes the endpoint.

    By default, endpoints are included unless x-mcp: false is specified or the CLI is run with --default-include false.

    # Optional root-level default
    x-mcp: true
    
    paths:
      /pets:
        x-mcp: false # exclude all ops under /pets
        get:
          x-mcp: true # include this operation anyway
    
      /users/{id}:
        get:
          # no x-mcp -> included by default
  5. Generate an MCP server via CLI

    main

    Use the openapi-mcp-generator command to scaffold a complete Node.js project from an OpenAPI specification. The generator creates a project with tsconfig.json, package.json, and a src/ directory containing the server logic and Zod validation schemas.

    Depending on your needs, you can choose different transport modes: stdio (default), web (SSE), or streamable-http.

    # Generate an MCP server (stdio)
    openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir
    
    # Generate an MCP web server with SSE
    openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir --transport=web --port=3000
    
    # Generate an MCP StreamableHTTP server
    openapi-mcp-generator --input path/to/openapi.json --output path/to/output/dir --transport=streamable-http --port=3000
  6. Test web-based MCP servers

    main

    When using web (SSE) or StreamableHTTP transports, the generator automatically creates a browser-based test client. To use it:

    1. Start the server using npm run start:web or npm run start:http.
    2. Open your browser and navigate to http://localhost:<port>.
    3. Use the provided interface to interact with your MCP server directly from the browser.
  7. Implement a custom authentication interface

    main

    If the built-in authentication (Basic, OAuth2, etc.) is insufficient, you can opt-in to a custom authentication flow using the --custom-auth flag.

    When enabled, the generator creates a src/auth.ts file in your project. You can then implement the applyCustomAuth function to intercept requests. If this function returns true, the built-in authentication logic is short-circuited.

    // src/auth.ts (Generated stub)
    export async function applyCustomAuth(ctx: {
      headers: Record<string, string>;
      queryParams: Record<string, any>;
      toolName: string;
      definition: any;
    }): Promise<boolean> {
      // Implement custom logic here
      // Return true to skip built-in auth
      return false;
    }
  8. Run a generated MCP server

    main

    After generating an MCP server, navigate to the output directory and install dependencies before running the server in your desired transport mode.

    Available modes:

    • stdio: Default mode for local process communication.
    • web (SSE): For web-based server communication.
    • StreamableHTTP: For HTTP-based streaming communication.
    cd path/to/output/dir
    npm install
    
    # Run in stdio mode
    npm start
    
    # Run in web server mode
    npm run start:web
    
    # Run in StreamableHTTP mode
    npm run start:http
  9. Configure OAuth2 authentication for the petstore-auth MCP server

    main

    The petstore-auth MCP server supports two authentication methods:

    1. Pre-acquired token: You provide a token that has already been obtained.
    2. Client credentials flow: The server automatically manages token acquisition using your credentials.

    To use the client credentials flow, you must set the following environment variables:

    export OAUTH_CLIENT_ID_PETSTORE_AUTH="your_client_id"
    export OAUTH_CLIENT_SECRET_PETSTORE_AUTH="your_client_secret"