Skip to content

Cannot Use authlib With MCP Clients #3231

@awickham10

Description

@awickham10

Initial Checks

Description

I have several MCP servers that I need to authenticate to with an OAuth 2.0 client credentials flow. Using authlib to help handle this seems like a reasonable choice, however, I cannot get it to work.

The examples below are snippets taken from scripts - not necessarily a fully working example. I'm just trying to illustrate the patterns I've attempted.

Example Code

## Sample 1 - Using this method results in an httpx client is already opened error.


http_client = AsyncOAuth2Client(
    client_id=self.config.client_id,
    client_secret=self.config.client_secret.get_secret_value(),
    token_endpoint_auth_method="client_secret_post",
    timeout=30.0,
)

# Fetch initial token
await http_client.fetch_token(
    token_endpoint,
    grant_type="client_credentials",
    **token_kwargs,
)

server = MCPServerStreamableHTTP(
    url=target_url,
    tool_prefix=self.config.name,
    max_retries=5,
    http_client=http_client,
)


## Sample 2 - Using this method results in a missing token error.


http_client = AsyncOAuth2Client(
    client_id=self.config.client_id,
    client_secret=self.config.client_secret.get_secret_value(),
    token_endpoint_auth_method="client_secret_post",
    timeout=30.0,
)

server = MCPServerStreamableHTTP(
    url=target_url,
    tool_prefix=self.config.name,
    max_retries=5,
    http_client=http_client,
)

Python, Pydantic AI & LLM client version

python 3.12
pydantic-ai 1.2.0
openai 2.4.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions