PrefectHQ/fastmcp · error · ValueError

Error building request for {self._route.method.upper()} {sel

Error message

Error building request for {self._route.method.upper()} {self._route.path}: {type(e).__name__}: {e}

What it means

While constructing the outbound httpx request for an OpenAPI tool (mapping arguments into path/query/body/headers, JSON-encoding the body, merging MCP headers), any exception is caught and re-raised as ValueError('Error building request for METHOD path: ...') from the original error.

Source

Thrown at fastmcp_slim/fastmcp/server/providers/openapi/components.py:224

            # merged with the directed headers taking priority.
            request = self._client.build_request(
                method=directed_request.method,
                url=str(directed_request.url.copy_with(query=None)),
                params=list(directed_request.url.params.multi_items()),
                headers=list(directed_request.headers.raw),
                # read() materializes streaming bodies (multipart files=)
                # that .content would refuse with RequestNotRead; idempotent
                # for plain byte bodies.
                content=directed_request.read(),
            )

            mcp_headers = get_http_headers()
            if mcp_headers:
                for key, value in mcp_headers.items():
                    if key not in request.headers:
                        request.headers[key] = value
        except Exception as e:
            raise ValueError(
                f"Error building request for {self._route.method.upper()} "
                f"{self._route.path}: {type(e).__name__}: {e}"
            ) from e

        # Send the request and process the response.
        try:
            logger.debug(
                f"run - sending request; headers: {_redact_headers(request.headers)}"
            )

            response = await _send_request(self._client, request)
            _raise_for_status(response)

            # Try to parse as JSON first
            try:
                result = response.json()

                # Handle structured content based on output schema

View on GitHub (pinned to 1f02114297)

Solutions

  1. Read the chained __cause__ to see the concrete failure
  2. Fix the tool call arguments to match the OpenAPI schema (serializable JSON values, correct names)
  3. Check custom route maps / parameter_map configuration
  4. Inspect MCP headers set via context for invalid values

Example fix

// before
tool({'due_date': datetime(2026, 1, 1)})
// after
tool({'due_date': '2026-01-01T00:00:00Z'})
Defensive patterns

Strategy: validation

Validate before calling

import json
def validate_args(tool_schema: dict, args: dict) -> bool:
    try:
        json.dumps(args)
    except (TypeError, ValueError):
        return False
    required = set(tool_schema.get('required', []))
    return required.issubset(args)

Try / catch

try:
    result = await tool.run(args)
except ValueError as e:
    if str(e).startswith('Error building request'):
        log.error('bad tool args: %s', e.__cause__)
        raise TypeError('invalid arguments for tool') from e
    raise

Prevention

When it happens

Trigger: Calling an OpenAPI tool with arguments that fail request construction: unserializable body values, wrong argument names, headers that violate httpx invariants, or a get_http_headers() failure.

Common situations: Passing non-JSON-serializable objects (datetime, bytes) in the tool arguments, mismatched parameter names vs the OpenAPI spec, custom header values containing invalid characters.

Related errors


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