Skip to content

[BUG] sanitize_for_json crashes on circular references (RecursionError) #189

Open

Description

@SarthakB11

Description

sanitize_for_json in server.py:74-83 recursively walks objects but has no cycle detection. If an sktime estimator contains circular references in its attributes (some do via parent/child pointers), this causes RecursionError and crashes the MCP server.

def sanitize_for_json(obj):
    if isinstance(obj, dict):
        return {str(k): sanitize_for_json(v) for k, v in obj.items()}  # no cycle check
    elif isinstance(obj, (list, tuple)):
        return [sanitize_for_json(item) for item in obj]  # no cycle check

The hasattr(obj, "__dict__") fallback on line 81 catches most non-dict/list objects by converting to str(), but dict/list cycles are uncaught.

How to reproduce

Any tool returning a result containing a circular reference will trigger this. Likely scenario: an estimator with a parent attribute pointing back to a container.

Suggested fix

Track visited objects by id():

def sanitize_for_json(obj, _seen=None):
    if _seen is None:
        _seen = set()
    obj_id = id(obj)
    if obj_id in _seen:
        return str(obj)
    _seen.add(obj_id)
    if isinstance(obj, dict):
        return {str(k): sanitize_for_json(v, _seen) for k, v in obj.items()}
    ...

Alternatively, wrap the top-level call in try/except RecursionError.

Found while reading the codebase for PR #114 work.

Activity

  1. SarthakB11 commented on Apr 13, 2026

    @SarthakB11
    ContributorAuthor

    Happy to open a PR for this — have a fix ready locally.

  2. added a commit that references this issue on Apr 18, 2026
  3. Shashankss1205 commented on Sep 6, 2026

    @Shashankss1205
    Collaborator

    Still reproducible on main; PR #515 adds the cycle guard and tests and is being merged now.

  4. Me-Priyank commented on Sep 20, 2026

    @Me-Priyank
    Contributor

    Looks like this was fixed by a26e3d1 (#515), sanitize_for_json has a _seen guard at server.py:159-168 now, with a test at test_sanitize.py:141. Might be closeable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions