rohitg00/ai-engineering-from-scratch · error · ValueError

state secret must not be empty

Error message

state secret must not be empty

What it means

Raised in RequestStateSigner.__init__ when the signing secret for the MRTR requestState is an empty string. The signer cannot produce an integrity-protected opaque value without key material, so construction is refused immediately rather than emitting unsigned, forgeable state.

Solutions

  1. Pass a non-empty, high-entropy secret generated per deployment (e.g. secrets.token_urlsafe(32))
  2. Load the secret from an environment variable and fail fast at startup if it is unset or blank
  3. Inject the secret via constructor argument in tests so no test constructs the signer with an empty key
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at certifications/claude/lessons/11-mcp-server-design-and-integration/code/main.py:75 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/b619237b31f260cc. Report an issue: GitHub.

Appendix: source

Thrown at certifications/claude/lessons/11-mcp-server-design-and-integration/code/main.py:75

            "string": lambda value: isinstance(value, str),
        }
        for name, value in arguments.items():
            if name not in properties:
                continue
            expected = properties[name].get("type")
            if expected not in checks:
                raise ValueError(f"unsupported schema type for {name}: {expected!r}")
            if not checks[expected](value):
                raise ValueError(f"{name} must be {expected}")
        return arguments


class RequestStateSigner:
    """Produces an opaque, integrity-protected MRTR requestState value."""

    def __init__(self, secret: bytes) -> None:
        if not secret:
            raise ValueError("state secret must not be empty")
        self.secret = secret

    def issue(self, method: str, tool: str, arguments: dict[str, Any]) -> str:
        payload = json.dumps(
            {"method": method, "tool": tool, "arguments": arguments},
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        encoded = base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
        signature = hmac.new(self.secret, encoded.encode("ascii"), hashlib.sha256).hexdigest()
        return f"{encoded}.{signature}"

    def verify(self, token: str, method: str, tool: str, arguments: dict[str, Any]) -> None:
        if not isinstance(token, str) or "." not in token:
            raise ValueError("requestState is malformed")
        encoded, supplied_signature = token.rsplit(".", 1)
        expected_signature = hmac.new(
            self.secret, encoded.encode("ascii"), hashlib.sha256

View on GitHub (pinned to 39ea8a1c6d)