oraios/serena · error · TypeError

gopls_settings must be a dict, got {type(gopls_settings).__n

Error message

gopls_settings must be a dict, got {type(gopls_settings).__name__}. Expected structure: {'buildFlags': ['-tags=foo'], 'env': {...}, ...}

What it means

TypeError raised by Gopls._validate_gopls_settings_dict when the user-supplied gopls_settings value is not a dict. The settings are forwarded verbatim as LSP initializationOptions, so anything other than a mapping is invalid. Called from _create_base_initialize_params and _raw_document_symbols_cache_fingerprint.

Source

Thrown at src/solidlsp/language_servers/gopls.py:151

        # Serena applies gopls settings at initialization time via initializationOptions
        # (Access settings directly to avoid extra INFO logging from CustomLSSettings.get.)
        gopls_settings = self._custom_settings.settings.get("gopls_settings")
        if gopls_settings:
            gopls_settings = self._validate_gopls_settings_dict(gopls_settings)

            # Validate JSON-serializability early: initializationOptions is sent over JSON-RPC.
            import json

            self._canonical_json_or_raise(json, gopls_settings)

            # Log keys only (and at DEBUG) to avoid leaking sensitive values and to reduce startup noise.
            log.debug("Applying gopls settings via initializationOptions: keys=%s", list(gopls_settings.keys()))
            initialize_params["initializationOptions"] = gopls_settings

        return initialize_params

    def _validate_gopls_settings_dict(self, gopls_settings: object) -> dict:
        if not isinstance(gopls_settings, dict):
            raise TypeError(
                f"gopls_settings must be a dict, got {type(gopls_settings).__name__}. "
                "Expected structure: {'buildFlags': ['-tags=foo'], 'env': {...}, ...}"
            )

        return gopls_settings

    def _canonical_json_or_raise(self, json_module: Any, data: object) -> str:
        try:
            return json_module.dumps(data, sort_keys=True, separators=(",", ":"))
        except (TypeError, ValueError) as exc:
            raise TypeError(
                "gopls_settings must be JSON-serializable (json.dumps). Use JSON-compatible values (dict/list/str/int/float/bool/null) and prefer string keys."
            ) from exc

    # Environment variables that influence Go build context and affect cached symbols.
    _CACHE_CONTEXT_ENV_KEYS = ("GOFLAGS", "GOOS", "GOARCH", "CGO_ENABLED")

View on GitHub (pinned to 7fcbca7e62)

Solutions

  1. Parse the settings into a dict before passing them (json.loads for JSON text)
  2. Pass settings as a keyword argument: gopls_settings={'buildFlags': [...], 'env': {...}}
  3. Check the config file section that supplies the settings — ensure it is a mapping, not a scalar
  4. If defaults are acceptable, omit gopls_settings entirely rather than passing None or an empty string

Example fix

// before
server = Gopls(..., gopls_settings='{"buildFlags": []}')  # JSON string
// after
import json
raw = '{"buildFlags": []}'
server = Gopls(..., gopls_settings=json.loads(raw))
Defensive patterns

Strategy: type-guard

Validate before calling

def validate_gopls_settings(settings):
    if settings is not None and not isinstance(settings, dict):
        raise TypeError(f'gopls_settings must be dict, got {type(settings).__name__}')

Type guard

def is_gopls_settings(value) -> bool:
    return isinstance(value, dict) and all(isinstance(k, str) for k in value)

# usage
if not is_gopls_settings(cfg.get('gopls_settings')):
    raise ValueError('gopls_settings must be a dict with string keys')

Try / catch

try:
    server = Gopls(..., gopls_settings=user_settings)
except TypeError as e:
    if 'gopls_settings must be a dict' in str(e):
        log.error('Fix configuration: gopls_settings must be a mapping')
        raise

Prevention

When it happens

Trigger: Passing gopls_settings as a string (e.g. JSON text), list, None, or a non-dict object when creating the Gopls server or computing the document-symbols cache fingerprint.

Common situations: Loading settings from a YAML/JSON config file that yields a string instead of a parsed dict; passing a JSON-encoded string where an object was expected; mixing up positional/keyword arguments.

Related errors


AI-assisted analysis of oraios/serena@7fcbca7e62 (2026-08-29). Data as JSON: /api/errors/6f640aa7cdaad726. Report an issue: GitHub.