PrefectHQ/fastmcp · error · ValueError

Invalid OpenAPI schema

Error message

Invalid OpenAPI schema: {error_details}

What it means

parse_openapi_to_http_routes validates the raw OpenAPI document against pydantic models for the spec version. If validation fails (spec doesn't match OpenAPI 3.0/3.1 required structure), it logs the pydantic errors and re-raises them wrapped as ValueError('Invalid OpenAPI schema: ...'). This means the document was readable but structurally invalid as an OpenAPI schema, not that the network or file access failed.

Solutions

  1. Read the pydantic error list embedded in the message — each entry gives the failing field path (loc), message, and type; fix those fields first.
  2. Validate the document with a standalone validator (e.g. `openapi-spec-validator`) before passing it, to get richer diagnostics.
  3. Confirm the document is OpenAPI 3.0/3.1, not Swagger 2.0 — convert 2.0 specs first (e.g. swagger2openapi).
  4. Re-export the spec from the source tool (FastAPI /postman/ gateway) ensuring a complete 3.x export, then diff against the failing one.
  5. Check that what you passed is the parsed JSON spec object, not a wrapper like {'spec': {...}} or an HTTP response object.

Example fix

// before
with open("spec.json") as f:
    routes = parse_openapi_to_http_routes(json.load(f))

// after
from openapi_spec_validator import validate_spec
with open("spec.json") as f:
    spec = json.load(f)
validate_spec(spec)  # raises with detailed diagnostics first
routes = parse_openapi_to_http_routes(spec)
Defensive patterns

Strategy: validation

Validate before calling

from openapi_spec_validator import validate_spec

def load_valid_spec(path: str) -> dict:
    with open(path) as f:
        spec = json.load(f)
    validate_spec(spec)
    return spec

routes = parse_openapi_to_http_routes(load_valid_spec("spec.json"))

Type guard

def is_openapi3(spec: object) -> bool:
    return (
        isinstance(spec, dict)
        and isinstance(spec.get("openapi"), str)
        and spec["openapi"].startswith("3.")
        and isinstance(spec.get("info"), dict)
        and isinstance(spec.get("paths"), dict)
    )

Try / catch

try:
    routes = parse_openapi_to_http_routes(spec)
except ValueError as e:
    logger.error("Spec rejected: %s", e)
    raise SystemExit("Fix the OpenAPI schema fields listed above") from e

Prevention

When it happens

Trigger: Calling parse_openapi_to_http_routes(spec) (directly or via OpenAPIClient/FastMCP.from_openapi-style integration) with a dict/JSON that violates required OpenAPI fields — missing `openapi` version key, missing `info`, missing `paths`, or fields with wrong types (e.g. `paths: []` instead of an object).

Common situations: Hand-written or LLM-generated specs missing required fields; Swagger 2.0 documents passed where 3.x is required; tools exporting incomplete specs; API gateways returning an HTML error page or truncated JSON that got parsed as a spec; minor-version fields typed incorrectly after spec upgrade.

Understand the failure class

Background: Schema validation failed / invalid input schema: payload rejected because its shape doesn't match the expected schema — this error's family across 28 libraries.

Related errors


AI-assisted analysis of PrefectHQ/fastmcp@1f02114297 (2026-08-29). Data as JSON: /api/errors/2b45dd56edff7672. Report an issue: GitHub.

Appendix: source

Thrown at fastmcp_slim/fastmcp/utilities/openapi/parser.py:107

                f"Successfully parsed OpenAPI 3.1 schema version: {openapi_31.openapi}"
            )
            parser = OpenAPIParser(
                openapi_31,
                Reference,
                Schema,
                Parameter,
                RequestBody,
                Response,
                Operation,
                PathItem,
                openapi_version,
            )
            return parser.parse()
    except ValidationError as e:
        logger.error(f"OpenAPI schema validation failed: {e}")
        error_details = e.errors()
        logger.error(f"Validation errors: {error_details}")
        raise ValueError(f"Invalid OpenAPI schema: {error_details}") from e


class OpenAPIParser(
    Generic[
        TOpenAPI,
        TReference,
        TSchema,
        TParameter,
        TRequestBody,
        TResponse,
        TOperation,
        TPathItem,
    ]
):
    """Unified parser for OpenAPI schemas with generic type parameters to handle both 3.0 and 3.1."""

    def __init__(
        self,

View on GitHub (pinned to 1f02114297)