Skip to content

bug(client): ADCPClient reports an MCP HTTP 401 as a connection failure #1282

Closed

Description

@bokelley

Summary

When an MCP agent answers with HTTP 401, ADCPClient reports a connection failure and tells the user to check the agent URI. It drops the status code and the WWW-Authenticate challenge, so a bad or missing token looks like a wrong URL. This happens on 8.0.0 and 8.0.0rc3.

Reproduction (adcp 8.0.0)

import asyncio
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer

from adcp import ADCPClient
from adcp.types import GetProductsRequest
from adcp.types.core import AgentConfig, Protocol


class Unauthorized(BaseHTTPRequestHandler):
    def do_POST(self):
        body = b'{"error":"unauthenticated"}'
        self.send_response(401)
        self.send_header("Content-Type", "application/json")
        self.send_header("WWW-Authenticate", 'Bearer realm="adcp", error="invalid_token"')
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    do_GET = do_POST


async def main():
    server = HTTPServer(("127.0.0.1", 0), Unauthorized)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    client = ADCPClient(AgentConfig(id="seller", agent_uri=f"http://127.0.0.1:{server.server_port}/mcp/",
                                    protocol=Protocol.MCP, auth_token="wrong-token", requires_auth=True))
    result = await client.get_products(GetProductsRequest(buying_mode="brief", brief="video"))
    print(result.error)

asyncio.run(main())

Output:

[Agent: seller] Failed to connect: Server returned an error response
  URI: http://127.0.0.1:<port>/mcp/
  Suggestion: Check that the agent URI is correct and the agent is running.
     Try testing with: python -m adcp test --config <agent-id>

Expected

An authentication error that names the HTTP status and the WWW-Authenticate error (invalid_token), and suggests checking the token and auth header. The A2A transport already reports HTTP Error 401: Client error '401 Unauthorized', which is enough to act on.

Why it matters

I hit this while probing a seller with the wrong token: the client sent me to check a URL that was correct. Buyer agents that read result.error to choose recovery also can't tell a credential problem from an unreachable agent.

Activity

  1. added
    bugSomething isn't working
    claude-triagingTriage routine is actively working on this issue (1-3 min)
    on Oct 2, 2026
  2. bokelley commented on Oct 2, 2026

    @bokelley
    ContributorAuthor

    Triage

    Classification: Bug
    Bucket(s): client (no client label exists in this repo — gap noted)
    Status: ready-to-implement
    Milestone: omitted — none named in issue

    What the experts said:

    • code-reviewer: Root cause confirmed. _ALL_HTTP_STATUS_ERROR_TYPES (the existing isinstance tuple covering both httpx and httpx2) must be used for chain-walking, not a fresh httpx import. _call_mcp_tool() must explicitly catch ADCPAuthenticationError before the bare except Exception and return TaskResult(FAILED, error="Authentication failed: HTTP 401 (...)") — leaving the choice unresolved is a blocker. Tests required for both the connection and tool-call paths.
    • dx-expert: Safe to surface WWW-Authenticate content (RFC 6750 public challenge, no credentials). A2A parity is the right target. Two additional fix points: short-circuit the URL discovery loop on 401/403 (don't probe alternate URL forms after an auth rejection), and apply the same fix to close_mcp_session() which has the same string-match gap.

    My take: The root cause is that _get_session()'s string-match on str(last_error) fails because the MCP SDK surfaces "Server returned an error response" — no status code in the text — so the branch that would raise ADCPAuthenticationError is never reached. The fix direction is clear, well-scoped, and fully non-breaking (corrects incorrect exception class; error text is diagnostic only).

    Implementation brief:

    • src/adcp/protocols/mcp.py — _get_session() (~line 662): Replace the str(last_error).lower() string-match with an exception chain walk. Check __cause__ then __context__ for isinstance(exc, _ALL_HTTP_STATUS_ERROR_TYPES) (the tuple already defined at ~line 61-64, covers both httpx and httpx2). On status_code in (401, 403), extract WWW-Authenticate from exc.response.headers and raise ADCPAuthenticationError(f"Authentication failed: HTTP {status_code} — {www_auth}", ...). Also break out of the URL discovery loop immediately on auth errors — probing /mcp vs /mcp/ after a 401 wastes round-trips and misleads.
    • src/adcp/protocols/mcp.py — _call_mcp_tool() (~line 943): Add ADCPAuthenticationError to the specific re-raise guard (alongside IdempotencyConflictError) or catch it before the bare except Exception and return TaskResult(FAILED, error=f"Authentication failed: HTTP {status_code} (...)"). The latter matches A2A's pattern (a2a.py:616-622) and is preferred.
    • src/adcp/protocols/mcp.py — close_mcp_session() (~line 1241): Apply the same chain-walk so 401/403 during session teardown raises ADCPAuthenticationError instead of ADCPConnectionError.
    • Move ADCPAuthenticationError to the top-level import block (currently lazily imported inside the branch).
    • Tests: Add cases in the MCP client test suite for: (a) _get_session() with chained httpx.HTTPStatusError(401) → ADCPAuthenticationError; (b) same for the httpx2 variant; (c) _call_mcp_tool() mid-call 401 → TaskResult(FAILED) with auth-specific message string.
    • Required checks: pytest on affected tests, mypy src/, ruff check . / black --check .

    Non-breaking rationale: no public symbols removed or renamed; the exception class fix corrects incorrect behavior consistent with existing A2A transport behavior; error message text is diagnostic only.


    Triaged by Claude Code. Session: https://claude.ai/code/session_014fEZrgJnTpaBnQXaDa5jFV


    Generated by Claude Code

  3. added and removed
    claude-triagingTriage routine is actively working on this issue (1-3 min)
    on Oct 2, 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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions