Skip to content

[Bug]: GitLab MCP OAuth succeeds but MCP test fails with Session terminated #5276

Open

Description

@majchrosoft

[Bug]: GitLab MCP OAuth succeeds but MCP test fails with Session terminated

Environment

  • OpenHands Agent Server: 1.49.4
  • OpenHands Agent Canvas: local installation
  • OS: Ubuntu 24.04
  • MCP server: GitLab Self-Managed
  • GitLab MCP endpoint: https://gitlab.klickrent.de/api/v4/mcp
  • Installation: local Agent Canvas / Agent Server

Bug description

I am trying to connect the GitLab MCP server to a local OpenHands Agent Canvas.

The OAuth flow starts correctly and OpenHands creates a temporary local OAuth callback server.

The browser redirects to GitLab, authentication succeeds, and the callback page displays:

Authentication successful

However, after the OAuth callback completes, OpenHands fails the MCP connection test and reports:

MCP test failed unexpectedly for server 'gitlab'

In some attempts the MCP client reports:

McpError: Session terminated

The problem happens after successful OAuth authentication, not during the initial authorization redirect.

Steps to reproduce

  1. Run OpenHands locally using Agent Canvas.

  2. Go to MCP configuration.

  3. Add an HTTP MCP server:

    https://gitlab.klickrent.de/api/v4/mcp

  4. Start the OAuth authorization flow.

  5. Authenticate in GitLab.

  6. Allow the OAuth request.

  7. The browser is redirected to the local OpenHands callback, for example:

    http://localhost:<dynamic-port>/callback

  8. The callback page reports:

    Authentication successful

  9. OpenHands then fails the MCP test.

Expected behavior

After successful OAuth authentication, OpenHands should store/use the OAuth credentials and successfully initialize the GitLab MCP session and list the available tools.

Actual behavior

OAuth authentication appears to complete successfully, but the MCP test fails immediately afterwards.

OpenHands logs show:

MCP OAuth authorization URL captured for job ...
MCP OAuth callback server ready for job ... at http://localhost:34483/callback
OAuth callback server started on http://localhost:34483
...
MCP test failed unexpectedly for server 'gitlab'

The failure occurs approximately 10 seconds after the OAuth callback server is started.

Additional observations

  • The OAuth callback is reachable locally and the browser displays Authentication successful.

  • This is a local OpenHands installation, not Docker.

  • The callback uses a dynamically allocated localhost port.

  • Restarting OpenHands / the machine and revoking the GitLab session can change the behavior, but the problem can recur.

  • The same GitLab MCP endpoint is being used:

    https://gitlab.klickrent.de/api/v4/mcp

There is already an OpenHands issue concerning OAuth MCP callbacks not being exposed from Docker containers, but this issue is different because the callback itself is successfully reached and completed on a local installation.

Could this be related to OAuth token persistence, scope handling, or the MCP session initialization performed after the OAuth callback?

Acceptance criteria

Added from the investigation in the comments: the OAuth flow works; GitLab then rejects the MCP request (for example 403 {"message":"403 Forbidden - MCP server not enabled for any of your groups"}), and OpenHands hides that reason.

  • When a remote MCP server (streamable HTTP or SSE) answers with an HTTP 4xx/5xx while connecting or listing tools, with or without OAuth, /api/mcp/test and the OAuth test flow return an error that names the HTTP status and the reason the server gave (WWW-Authenticate error_description/error, a JSON message/error/detail/JSON-RPC error.message, or the body text, capped at 300 characters).
  • This also applies when the mcp client reduces the response to Server returned an error response, Session terminated or Not Found.
  • The error does not include URL userinfo, the query string or the path.
  • Agent Canvas shows the message in the MCP test result, and the agent-server logs it.
  • Successful connections, OAuth and SSE streams work as before.
  • Tests cover streamable HTTP and SSE.

Reproduction on main (91e8b5b)

I ran Agent Canvas main (46f20aba) against an agent-server built from SDK main 91e8b5b. The MCP server was a local mock that does real OAuth (dynamic client registration, consent page, token) and then answers MCP requests the way GitLab does when MCP is off for the user: 403 {"message": "403 Forbidden - MCP server not enabled for any of your groups"}. Authorization completes. The Canvas test then shows only Connection failed: MCPError: Server returned an error response, with no status and no reason.

Before: OAuth succeeds, then Canvas shows only 'MCPError: Server returned an error response'

With the fix in #5349, the same steps show HTTP 403 Forbidden from http://127.0.0.1:9301: 403 Forbidden - MCP server not enabled for any of your groups:

After (#5349)

This comment/PR was created by an AI agent (OpenHands) on behalf of Graham Neubig.

Activity

  1. all-hands-bot commented on Sep 23, 2026

    @all-hands-bot
    Collaborator

    The following comments were added by the OpenHands AI agent.

    Decision needed

    I could not safely finalize a scope for this from the repository alone, because the reported symptom sits at a boundary this repo does not fully control, and the two log lines point in different directions.

    What the code shows: MCP test failed unexpectedly for server 'gitlab' is the generic except Exception fallback in _probe_mcp_server (openhands-agent-server/openhands/agent_server/mcp_router.py), which logs the real exception at exc_info=True. McpError: Session terminated is emitted by the bundled mcp client's streamable-http transport when a POST to the MCP endpoint returns HTTP 404 — i.e. the server ended the session, not an authentication rejection. That does not match the closed #4818/#4821 post-consent crash (already in 1.49.4), and it does not match open #4843's pre-registration redirect-URI symptom ("invalid callback URL" during authorization), since here authorization succeeds.

    To set a real, testable scope I need:

    1. The full traceback behind MCP test failed unexpectedly for server 'gitlab' (the exc_info=True stack), plus the OAuth/timeout lines immediately before it. This distinguishes an OAuth token-persistence failure from an MCP session/transport failure.
    2. The resolved fastmcp and mcp versions in the failing environment (pip show fastmcp mcp / uv pip list), and whether the server is configured as http or sse.
    3. Whether the same endpoint works from a plain MCP client outside OpenHands (for example a minimal fastmcp client script using the obtained token). If it does not, the defect is likely in the GitLab Self-Managed MCP endpoint rather than this repository.
    4. Server-side logs from gitlab.klickrent.de for the failing request — specifically whether it returns 404 for the post-callback session POST, and any session-expiry or protocol-version message.

    Once I know whether this is agent-server OAuth state handling, MCP client transport behavior, or upstream GitLab endpoint behavior, I can scope it and write observable acceptance criteria. I have not added ready-for-dev.

  2. majchrosoft commented on Sep 23, 2026

    @majchrosoft
    Author

    Thanks. I went back through the logs from the failing attempts and here is everything I currently have.

    Environment

    • OS: Ubuntu 24.04
    • OpenHands Agent Canvas: local installation
    • OpenHands Agent Server: 1.49.4
    • GitLab Self-Managed MCP endpoint:
      https://gitlab.klickrent.de/api/v4/mcp
    • The Agent Server is running locally on 127.0.0.1:18000.
    • The OAuth callback server is also created locally on a dynamically allocated localhost port.

    The actual process topology during the failing run was:

    agent-canvas
      └── uv
           └── python agent-server --host 127.0.0.1 --port 18000
    

    The relevant process was:

    /home/majcher/.cache/uv/archive-v0/udokEMN4QU_0mg2z/bin/python \
    /home/majcher/.cache/uv/archive-v0/udokEMN4QU_0mg2z/bin/agent-server \
    --import-modules canvas_ui_tool \
    --host 127.0.0.1 \
    --port 18000
    

    Failing attempt #1

    OpenHands log:

    17:37:08 [agent-server] INFO     127.0.0.1:42362 - "GET /server_info HTTP/1.1" 200
    17:37:09 [agent-server] INFO     MCP OAuth authorization URL captured for job 5cafbae40a2c4e9397a1a0de096c8d9b  mcp_router.py:463
    17:37:09 [agent-server] INFO     MCP OAuth callback server ready for job 5cafbae40a2c4e9397a1a0de096c8d9b at http://localhost:54181/callback  mcp_router.py:475
    17:37:09 [agent-server] [09/22/26 19:37:09] INFO     🎧 OAuth callback server started on    oauth.py:381
    17:37:09 [agent-server] http://localhost:54181
    17:37:24 [ingress] (node:14086) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 timeout listeners added to [Socket]. MaxListeners is 10. Use emitter.setMaxListeners() to show where the warning was created
    17:37:25 [agent-server] WARNING  MCP test failed unexpectedly for server 'gitlab'  mcp_router.py:593
    

    This attempt is from the full OpenHands log captured on September 22.

    Failing attempt #2

    A second independent attempt on September 23 produced:

    15:02:24 [agent-server] INFO     127.0.0.1:42562 - "GET /server_info HTTP/1.1" 200
    15:02:25 [agent-server] INFO     MCP OAuth authorization URL captured for job 9ad14fb4a1c84127ba1978975cd3e480  mcp_router.py:463
    15:02:25 [agent-server] INFO     MCP OAuth callback server ready for job 9ad14fb4a1c84127ba1978975cd3e480 at http://localhost:34483/callback  mcp_router.py:475
    15:02:25 [agent-server] [09/23/26 17:02:25] INFO     🎧 OAuth callback server started on    oauth.py:381
    15:02:25 [agent-server] http://localhost:34483
    15:02:35 [agent-server] WARNING  MCP test failed unexpectedly for server 'gitlab'  mcp_router.py:593
    15:02:36 [ingress] (node:39902) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 timeout listeners added to [Socket]. MaxListeners is 10. Use emitter.setMaxListeners() to show where this warning was created
    15:02:36 [automation] {"message": "::1:0 - \"GET /api/automation/health HTTP/1.1\" 200", "severity": "INFO"}
    15:02:36 [agent-server] INFO     Settings accessed  settings_router.py:160
    

    Again, the callback server is started successfully on localhost and the generic MCP failure happens afterwards.

    OAuth callback behavior

    During the OAuth flow, the browser actually reaches the local callback and displays:

    Authentication successful
    

    So the authorization flow gets as far as the local callback.

    The callback is not an externally exposed URL. It is dynamically created as:

    http://localhost:<dynamic-port>/callback
    

    For example:

    http://localhost:54181/callback
    

    and in another attempt:

    http://localhost:34483/callback
    

    Important limitation

    The logs I have captured do NOT contain the traceback behind:

    MCP test failed unexpectedly for server 'gitlab'
    

    The only line emitted by OpenHands at that point is the generic warning from:

    mcp_router.py:593
    

    I therefore do not currently have the exc_info=True traceback requested in your comment.

    I also do not currently have the exact resolved versions from the failing environment for:

    fastmcp
    mcp
    

    and I have not yet captured a server-side GitLab log showing the HTTP response to the MCP session POST.

    Additional observation

    The failure is reproducible across multiple fresh OpenHands starts. In both captured runs the sequence is:

    MCP OAuth authorization URL captured
            ↓
    local OAuth callback server started
            ↓
    OAuth callback completes in the browser
            ↓
    ~10-15 seconds later
            ↓
    MCP test failed unexpectedly for server 'gitlab'
    

    I am happy to provide the pip show fastmcp mcp output and a fresh run with debug logging / the complete traceback if that is needed to distinguish OAuth state/token handling from MCP streamable-HTTP session initialization.

  3. majchrosoft commented on Sep 23, 2026

    @majchrosoft
    Author

    i can see in my gitlab account that the session is established and active. I can revoke it on demand from gtilab account

  4. majchrosoft commented on Sep 23, 2026

    @majchrosoft
    Author

    Thanks. I checked the environment and the logs again.

    Environment

    • OS: Ubuntu 24.04
    • OpenHands Agent Server: 1.49.4
    • OpenHands Agent Canvas: local installation
    • GitLab Self-Managed MCP endpoint:
    https://gitlab.klickrent.de/api/v4/mcp
    

    The Agent Server is running locally on:

    127.0.0.1:18000
    

    The relevant Python process is:

    /home/majcher/.cache/uv/archive-v0/udokEMN4QU_0mg2z/bin/python \
    /home/majcher/.cache/uv/archive-v0/udokEMN4QU_0mg2z/bin/agent-server \
    --import-modules canvas_ui_tool \
    --host 127.0.0.1 \
    --port 18000
    

    Installed MCP packages

    I checked the exact Python environment used by the Agent Server:

    fastmcp==3.4.7
    mcp==1.30.0
    

    Command used:

    /home/majcher/.cache/uv/archive-v0/udokEMN4QU_0mg2z/bin/python - <<'PY'
    from importlib.metadata import version, PackageNotFoundError
    
    for p in ("fastmcp", "mcp"):
        try:
            print(f"{p}=={version(p)}")
        except PackageNotFoundError:
            print(f"{p}: NOT INSTALLED")
    PY

    Output:

    fastmcp==3.4.7
    mcp==1.30.0
    

    OAuth / MCP failure

    I have two independent failing runs.

    September 22

    17:37:08 [agent-server] INFO     127.0.0.1:42362 - "GET /server_info HTTP/1.1" 200
    17:37:09 [agent-server] INFO     MCP OAuth authorization URL captured for job 5cafbae40a2c4e9397a1a0de096c8d9b  mcp_router.py:463
    17:37:09 [agent-server] INFO     MCP OAuth callback server ready for job 5cafbae40a2c4e9397a1a0de096c8d9b at http://localhost:54181/callback  mcp_router.py:475
    17:37:09 [agent-server] [09/22/26 19:37:09] INFO     🎧 OAuth callback server started on    oauth.py:381
    17:37:09 [agent-server] http://localhost:54181
    17:37:24 [ingress] (node:14086) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 timeout listeners added to [Socket]. MaxListeners is 10. Use emitter.setMaxListeners() to show where the warning was created
    17:37:25 [agent-server] WARNING  MCP test failed unexpectedly for server 'gitlab'  mcp_router.py:593
    

    September 23

    15:02:24 [agent-server] INFO     127.0.0.1:42562 - "GET /server_info HTTP/1.1" 200
    15:02:25 [agent-server] INFO     MCP OAuth authorization URL captured for job 9ad14fb4a1c84127ba1978975cd3e480  mcp_router.py:463
    15:02:25 [agent-server] INFO     MCP OAuth callback server ready for job 9ad14fb4a1c84127ba1978975cd3e480 at http://localhost:34483/callback  mcp_router.py:475
    15:02:25 [agent-server] [09/23/26 17:02:25] INFO     🎧 OAuth callback server started on    oauth.py:381
    15:02:25 [agent-server] http://localhost:34483
    15:02:35 [agent-server] WARNING  MCP test failed unexpectedly for server 'gitlab'  mcp_router.py:593
    15:02:36 [ingress] (node:39902) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 timeout listeners added to [Socket]. Use emitter.setMaxListeners() to show where the warning was created
    

    In the browser, after GitLab authentication, the local OAuth callback page displayed:

    Authentication successful
    

    So the browser did reach the OpenHands callback.

    Important limitation

    The logs I have do NOT contain the actual exception/traceback behind:

    MCP test failed unexpectedly for server 'gitlab'
    

    Although the log points to:

    mcp_router.py:593
    

    there is no traceback in the captured output.

    I also cannot currently determine the GitLab transport type from ~/.openhands/settings.json.

    The only MCP entry currently present there is an unrelated GitHub server:

    "mcp_config": {
      "github": {
        "url": "https://api.githubcopilot.com/mcp/",
        "transport": "http",
        "auth": {
          "strategy": "api_key",
          "value": "..."
        },
        "enabled": true
      }
    }

    There is currently no gitlab entry in ~/.openhands/settings.json.

    This may simply mean that the failed GitLab configuration is not persisted after the failed test.

    Process topology

    During the failure, the Agent Canvas process tree was:

    agent-canvas
      └── uv
           └── python agent-server
    

    The relevant agent-server process was PID 39796.

    Its stdout/stderr were connected through Unix sockets to the parent agent-canvas process rather than directly to the terminal.

    What I have not verified yet

    I have not yet:

    1. Captured the full exc_info=True traceback from mcp_router.py:593.
    2. Independently tested the GitLab MCP endpoint with a separate MCP client.
    3. Checked the GitLab server-side logs for the corresponding MCP request / HTTP status.

    The reproducible sequence from my side is:

    OpenHands starts OAuth
            ↓
    GitLab authentication
            ↓
    Browser shows "Authentication successful"
            ↓
    localhost:<dynamic-port>/callback is reached
            ↓
    ~10–15 seconds
            ↓
    MCP test failed unexpectedly for server 'gitlab'
    

    The issue is reproducible with both fresh OpenHands starts shown above.

  5. majchrosoft commented on Sep 24, 2026

    @majchrosoft
    Author

    there was no problem on gitlab server side. YOu can easily reproduce that bugged behavior in gitlab.com

  6. majchrosoft commented on Sep 25, 2026

    @majchrosoft
    Author

    Hi,

    I forked You repo and try to make some debug. Finally i have possible answer - the mcp server (the url responds with json) but it must be enabled by the owner of the top-group in gitlab . settings/general/permissions.../mcp

    Next week I will reach the owner and ask him aobut that setting.
    Most probable cause - that setting is turned off. - the response then is 403 - the oauth authorization works, but the mcp server is forbidden

  7. seek-far commented on Sep 25, 2026

    @seek-far

    Hi,

    I have tested the issue with both gitlab.com and my self-hosted GitLab. My testing and debugging on gitlab.com were similar to yours: after I enabled MCP in the top-level group, the MCP connection worked. Details are as follows.

    1. Test with gitlab.com
    First I tested with my account A. The test failed with the same 403, and the log matches yours (MCP test failed unexpectedly for server ... ). I wrote a small standalone debugging program using FastMCP, independent of OpenHands, and found that GitLab actually responded with the failure reason:

    {"message":"403 Forbidden - MCP server not enabled for any of your groups"}
    

    My account A does not belong to any group.

    Then I registered a new account B on gitlab.com and created a top-level group with B as the owner. In that group, I checked "Allow connection to GitLab" under Settings → General → Permissions and group features → MCP client access. But the test still failed. I tested again 10 minutes later, and it failed again. About 90 minutes later, my third test succeeded, so the setting may take a while to take effect.

    2. Test with my self-hosted GitLab
    The GitLab version is GitLab CE 18.11.3. The MCP connection succeeded for a non-administrator account that does not belong to any group. Note that the MCP access setting was introduced in GitLab 19.0 (generally available in 19.2), so 18.11 has no such setting.

    The OAuth flow in OpenHands works correctly, but the error reporting could be improved to ease troubleshooting. GitLab's response body states the reason clearly, but OpenHands currently doesn't surface it anywhere: the agent-server traceback contains only the status code, not the response body; in the Agent Canvas aggregated log even that traceback is missing, leaving only the single line MCP test failed unexpectedly; and the UI only shows HTTPStatusError: Client error '403 Forbidden' .... I plan to investigate further and may open a PR referencing this issue to improve this.

    When you contact the owner next week to enable the setting, it would be great if you could come back and share the result. Thanks.

  8. onatozmenn commented on Sep 27, 2026

    @onatozmenn
    Contributor

    I'll take the error-surfacing part: _probe_mcp_server currently swallows the real probe failure behind the generic MCP test failed unexpectedly message, so a GitLab 403 like MCP server not enabled for any of your groups never reaches the user. Plan is to surface the underlying status/body in the probe result while keeping the probe non-fatal. Will open a PR shortly.

  9. onatozmenn commented on Sep 27, 2026

    @onatozmenn
    Contributor

    Quick update: PR #5346 implementing the probe error-surfacing is open, but its description check now requires this issue to carry ready-for-dev (post-rollout issue, no labels yet). Could a maintainer please add that label? Happy to adjust scope if you'd rather keep this issue unlabeled.

  10. majchrosoft commented on Sep 27, 2026

    @majchrosoft
    Author

    thanks a lot!

  11. seek-far commented on Sep 27, 2026

    @seek-far

    I have opened #5349 for the error-surfacing part of this issue. #5346 targets the same part; in my humble opinion, it may not fully achieve the goal in Agent Canvas, for two reasons I found while testing:

    #5349 keeps error_kind="unknown", reads the body in the SDK, and includes before/after Agent Canvas screenshots against gitlab.com and Asana. I'm happy to go with whichever approach the maintainers prefer, or to combine them.

    Could a maintainer please consider adding ready-for-dev to this issue? Both PRs need it to pass the PR description check.

  12. onatozmenn commented on Oct 23, 2026

    @onatozmenn
    Contributor

    This is a valid MCP bug and a fix is ready in #5346. The PR's Validate PR description check is blocked only because this issue is missing the ready-for-dev label. Could a maintainer add it so the fix can move forward?

  13. added a commit that references this issue on Nov 13, 2026
    5d5bbb5
  14. added
    ready-for-dev
    and removed
    ready-for-dev
    on Nov 13, 2026
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