---
title: middleware
sidebarTitle: middleware
---

# `keycardai.mcp.integrations.fastmcp.middleware`


Access middleware for FastMCP.

This module provides AccessMiddleware, which manages the lifecycle of
KeyCard's OAuth client and provides automated token exchange through
the grant decorator.


## Classes

### `AccessMiddlewareSettings` <sup><a href="https://github.com/keycardai/python-sdk/blob/main/src/keycardai/mcp/integrations/fastmcp/middleware.py#L30" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>


Settings for access middleware.


### `AccessMiddleware` <sup><a href="https://github.com/keycardai/python-sdk/blob/main/src/keycardai/mcp/integrations/fastmcp/middleware.py#L37" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>


Middleware that manages OAuth client lifecycle and provides automated token exchange.

This middleware initializes and manages a KeyCard OAuth client and provides
the grant decorator for automated token exchange operations. It follows the
FastMCP middleware protocol and integrates with the context system.

Features:
- Lazy initialization of OAuth client on first tool call
- Automatic client registration and metadata discovery
- grant() decorator for automated token exchange
- Support for single or multiple resource access
- Thread-safe initialization with async locking
- Integration with FastMCP context state system


**Methods:**

#### `on_call_tool` <sup><a href="https://github.com/keycardai/python-sdk/blob/main/src/keycardai/mcp/integrations/fastmcp/middleware.py#L140" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python
on_call_tool(self, context: MiddlewareContext, call_next: CallNext) -> any
```

Ensure OAuth client is available for token exchange operations.

This method is called before every tool execution and ensures that:
1. OAuth client is properly initialized for internal use
2. Ready to handle token exchange requests via grant decorator

**Args:**
- `context`: Middleware context containing the tool call
- `call_next`: Next middleware or tool handler in the chain

**Returns:**
- Result from the next handler in the chain


#### `grant` <sup><a href="https://github.com/keycardai/python-sdk/blob/main/src/keycardai/mcp/integrations/fastmcp/middleware.py#L158" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python
grant(self, resources: str | list[str])
```

Decorator for automatic delegated token exchange.

This decorator automates the OAuth token exchange process for accessing
external resources on behalf of authenticated users. It:

1. Extracts the user's bearer token from the FastMCP context
2. Performs RFC 8693 token exchange for the specified resource(s)
3. Makes tokens available through ctx.keycardadi_access()
4. Handles all error cases gracefully

**Args:**
- `resources`: Target resource URL(s) for token exchange.
      Can be a single string or list of strings.
      (e.g., "https\://www.googleapis.com/calendar/v3" or
       ["https\://www.googleapis.com/calendar/v3", "https\://www.googleapis.com/drive/v3"])

The decorated function receives:
- Enhanced context with keycardai namespace available via ctx.get_state("keycardai")
- All original function parameters unchanged

Error handling:
- Returns structured error response if token exchange fails
- Preserves original function signature and behavior
- Provides detailed error messages for debugging


### `KeycardaiNamespace` <sup><a href="https://github.com/keycardai/python-sdk/blob/main/src/keycardai/mcp/integrations/fastmcp/middleware.py#L268" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>


Namespace object for keycardai access methods.


**Methods:**

#### `access` <sup><a href="https://github.com/keycardai/python-sdk/blob/main/src/keycardai/mcp/integrations/fastmcp/middleware.py#L274" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python
access(self, resource: str) -> TokenResponse
```

Get token response for the specified resource.
Args:
    resource: The resource URL to get token response for
Returns:
    TokenResponse object with access_token attribute
Raises:
    KeyError: If resource was not granted in the decorator

