Metadata-Version: 2.4
Name: keycardai-mcp-fastmcp
Version: 0.17.0
Summary: FastMCP integration for Keycard OAuth client with automated token exchange and authentication
Project-URL: Homepage, https://github.com/keycardai/python-sdk
Project-URL: Repository, https://github.com/keycardai/python-sdk
Project-URL: Documentation, https://docs.keycardai.com
Project-URL: Issues, https://github.com/keycardai/python-sdk/issues
Author-email: Keycard <support@keycard.ai>
License: MIT
Keywords: authentication,fastmcp,keycard,mcp,model-context-protocol,oauth,token-exchange
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP :: Session
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: fastmcp==2.13.0
Requires-Dist: httpx>=0.27.2
Requires-Dist: keycardai-mcp>=0.15.0
Requires-Dist: keycardai-oauth>=0.6.0
Requires-Dist: pydantic-settings>=2.7.1
Requires-Dist: pydantic>=2.11.7
Provides-Extra: test
Requires-Dist: pytest-asyncio>=1.1.0; extra == 'test'
Requires-Dist: pytest>=8.4.1; extra == 'test'
Description-Content-Type: text/markdown

# Keycard FastMCP Integration

A Python package that provides seamless integration between Keycard and FastMCP servers, enabling secure token exchange and authentication for MCP tools.

## Requirements

- **Python 3.9 or greater**
- Virtual environment (recommended)

## Setup Guide

### Option 1: Using uv (Recommended)

If you have [uv](https://docs.astral.sh/uv/) installed:

```bash
# Create a new project with uv
uv init my-fastmcp-project
cd my-fastmcp-project

# Create and activate virtual environment
uv venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
```

### Option 2: Using Standard Python

```bash
# Create project directory
mkdir my-fastmcp-project
cd my-fastmcp-project

# Create and activate virtual environment
python3 -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Upgrade pip (recommended)
pip install --upgrade pip
```

## Installation

```bash
uv add keycardai-mcp-fastmcp
```

or

```bash
pip install keycardai-mcp-fastmcp
```

## Quick Start

Add Keycard authentication to your existing FastMCP server:

### Install the Package

```bash
uv add keycardai-mcp-fastmcp
```

### Get Your Keycard Zone ID

1. Sign up at [keycard.ai](https://keycard.ai)
2. Navigate to Zone Settings to get your zone ID
3. Configure your preferred identity provider (Google, Microsoft, etc.)
4. Create an MCP resource in your zone

### Add Authentication to Your FastMCP Server

```python
from fastmcp import FastMCP, Context
from keycardai.mcp.integrations.fastmcp import AuthProvider

# Configure Keycard authentication (recommended: use zone_id)
auth_provider = AuthProvider(
    zone_id="your-zone-id",  # Get this from keycard.ai
    mcp_server_name="My Secure FastMCP Server",
    mcp_base_url="http://127.0.0.1:8000/"  # Note: trailing slash will be added automatically
)

# Get the RemoteAuthProvider for FastMCP
auth = auth_provider.get_remote_auth_provider()

# Create authenticated FastMCP server
mcp = FastMCP("My Secure FastMCP Server", auth=auth)

@mcp.tool()
def hello_world(name: str) -> str:
    return f"Hello, {name}!"

if __name__ == "__main__":
    mcp.run(transport="streamable-http")
```

### Add access delegation to tool calls

```python
from fastmcp import FastMCP, Context
from keycardai.mcp.integrations.fastmcp import AuthProvider, AccessContext

# Configure Keycard authentication (recommended: use zone_id)
auth_provider = AuthProvider(
    zone_id="your-zone-id",  # Get this from keycard.ai
    mcp_server_name="My Secure FastMCP Server",
    mcp_base_url="http://127.0.0.1:8000/"  # Note: trailing slash will be added automatically
)

# Get the RemoteAuthProvider for FastMCP
auth = auth_provider.get_remote_auth_provider()

# Create authenticated FastMCP server
mcp = FastMCP("My Secure FastMCP Server", auth=auth)

# Example with token exchange for external API access
@mcp.tool()
@auth_provider.grant("https://api.example.com")
def call_external_api(ctx: Context, query: str) -> str:
    # Get access context to check token exchange status
    access_context: AccessContext = ctx.get_state("keycardai")
    
    # Check for errors before accessing token
    if access_context.has_errors():
        return f"Error: Failed to obtain access token - {access_context.get_errors()}"
    
    # Access delegated token through context namespace
    token = access_context.access("https://api.example.com").access_token
    # Use token to call external API
    return f"Results for {query}"

if __name__ == "__main__":
    mcp.run(transport="streamable-http")
```

### 🎉 Your FastMCP server is now protected with Keycard authentication! 🎉

## Working with AccessContext

When using the `@grant()` decorator, tokens are made available through the `AccessContext` object. This object provides robust error handling and status checking for token exchange operations.

The `@grant()` decorator avoids raising exceptions. Instead, it exposes error information via associated metadata. 
You can check if the context encountered errors by calling the `has_errors()` method.

### Basic Usage

```python
from keycardai.mcp.integrations.fastmcp import AccessContext

@mcp.tool()
@auth_provider.grant("https://api.example.com")
def my_tool(ctx: Context, user_id: str) -> str:
    # Get the access context
    access_context: AccessContext = ctx.get_state("keycardai")
    
    # Always check for errors first
    if access_context.has_errors():
        # Handle the error case
        errors = access_context.get_errors()
        return f"Authentication failed: {errors}"
    
    # Access the token for the specific resource
    token = access_context.access("https://api.example.com").access_token
    
    # Use the token in your API calls
    headers = {"Authorization": f"Bearer {token}"}
    # Make your API request...
    return f"Success for user {user_id}"
```

### Multiple Resources

You can request tokens for multiple resources in a single decorator:

```python
@mcp.tool()
@auth_provider.grant(["https://api.example.com", "https://other-api.com"])
def multi_resource_tool(ctx: Context) -> str:
    access_context: AccessContext = ctx.get_state("keycardai")
    
    # Check overall status
    status = access_context.get_status()  # "success", "partial_error", or "error"
    
    if status == "error":
        # Global error - no tokens available
        return f"Global error: {access_context.get_error()}"
    
    elif status == "partial_error":
        # Some resources succeeded, others failed
        successful = access_context.get_successful_resources()
        failed = access_context.get_failed_resources()
        
        # Work with successful resources only
        for resource in successful:
            token = access_context.access(resource).access_token
            # Use token...
        
        return f"Partial success: {len(successful)} succeeded, {len(failed)} failed"
    
    else:  # status == "success"
        # All resources succeeded
        token1 = access_context.access("https://api.example.com").access_token
        token2 = access_context.access("https://other-api.com").access_token
        # Use both tokens...
        return "All resources accessed successfully"
```

### Error Handling Methods

The `AccessContext` provides several methods for checking errors:

```python
# Check if there are any errors (global or resource-specific)
if access_context.has_errors():
    # Handle any error case

# Check for global errors only
if access_context.has_error():
    global_error = access_context.get_error()

# Check for specific resource errors
if access_context.has_resource_error("https://api.example.com"):
    resource_error = access_context.get_resource_errors("https://api.example.com")

# Get all errors (global + resource-specific)
all_errors = access_context.get_errors()

# Get status summary
status = access_context.get_status()  # "success", "partial_error", or "error"

# Get lists of successful/failed resources
successful_resources = access_context.get_successful_resources()
failed_resources = access_context.get_failed_resources()
```

## Important Configuration Notes

### URL Slash Requirement

⚠️ **Important**: The `mcp_base_url` parameter will automatically have a trailing slash (`/`) appended if not present. This is required for proper JWT audience validation with FastMCP.

**When configuring your Keycard Resource**, ensure the resource URL in your Keycard zone settings matches exactly, including the trailing slash:

```python
# This configuration...
auth_provider = AuthProvider(
    zone_id="your-zone-id",
    mcp_base_url="http://localhost:8000"  # No trailing slash
)

# Will become "http://localhost:8000/" internally
# So your Keycard Resource must be configured as: http://localhost:8000/
```

### Zone Configuration

Keycard zones are isolated environments for authentication and authorization. You can configure zone settings explicitly in code or automatically discover them from environment variables.

#### Configuration Methods

**1. Explicit Configuration (Recommended for Production)**

```python
from keycardai.mcp.integrations.fastmcp import AuthProvider

# Using zone_id (constructs zone URL automatically)
auth_provider = AuthProvider(
    zone_id="your-zone-id",
    mcp_server_name="My MCP Server",
    mcp_base_url="http://localhost:8000"
)

# Using explicit zone_url
auth_provider = AuthProvider(
    zone_url="https://your-zone-id.keycard.cloud",
    mcp_server_name="My MCP Server",
    mcp_base_url="http://localhost:8000"
)

# Using custom base_url with zone_id
auth_provider = AuthProvider(
    zone_id="your-zone-id",
    base_url="https://custom.keycard.example.com",
    mcp_server_name="My MCP Server",
    mcp_base_url="http://localhost:8000"
)
```

**2. Environment Variable Discovery**

The SDK automatically discovers zone configuration from environment variables:

```bash
# Option 1: Set zone_id (URL will be constructed)
export KEYCARD_ZONE_ID="your-zone-id"

# Option 2: Set explicit zone URL
export KEYCARD_ZONE_URL="https://your-zone-id.keycard.cloud"

# Option 3: Customize base URL for zone construction
export KEYCARD_ZONE_ID="your-zone-id"
export KEYCARD_BASE_URL="https://custom.keycard.example.com"
```

```python
from keycardai.mcp.integrations.fastmcp import AuthProvider

# Automatically discovers zone configuration from environment
auth_provider = AuthProvider(
    mcp_server_name="My MCP Server",
    mcp_base_url="http://localhost:8000"
)
```

#### Configuration Precedence

When multiple zone configuration methods are present, the SDK follows this precedence order (highest to lowest):

1. **Explicit `zone_url` parameter** - Always takes priority
2. **`KEYCARD_ZONE_URL` environment variable** - Direct zone URL
3. **Explicit `zone_id` parameter** - Combined with base_url to construct zone URL
4. **`KEYCARD_ZONE_ID` environment variable** - Combined with base_url to construct zone URL
5. **Error** - At least one zone configuration method is required

For `base_url`, the precedence is:
1. **Explicit `base_url` parameter** - Custom base URL
2. **`KEYCARD_BASE_URL` environment variable** - Custom base URL from environment
3. **Default: `https://keycard.cloud`** - Standard Keycard cloud URL

#### Environment Variables Reference

| Environment Variable | Purpose | Default Value |
|---------------------|---------|---------------|
| `KEYCARD_ZONE_ID` | Zone identifier for constructing zone URL | None (required if zone_url not set) |
| `KEYCARD_ZONE_URL` | Complete zone URL (overrides zone_id) | None |
| `KEYCARD_BASE_URL` | Base URL for zone construction | `https://keycard.cloud` |

### Application Credentials for Token Exchange

To enable token exchange (required for the `@grant` decorator), you need to configure application credentials. The SDK supports multiple credential types and provides automatic discovery via environment variables.

#### Credential Types

The SDK supports three types of application credentials:

1. **ClientSecret** - OAuth client credentials (client_id/client_secret) issued by Keycard
2. **WebIdentity** - Private key JWT authentication for MCP servers
3. **EKSWorkloadIdentity** - AWS EKS Pod Identity for Kubernetes deployments

#### Configuration Methods

##### 1. Explicit Configuration (Recommended for Production)

Explicitly provide credentials when creating the `AuthProvider`:

```python
from keycardai.mcp.integrations.fastmcp import AuthProvider, ClientSecret

# Client Secret credentials
auth_provider = AuthProvider(
    zone_id="your-zone-id",
    mcp_server_name="My FastMCP Service",
    mcp_base_url="http://localhost:8000/",
    application_credential=ClientSecret(("your_client_id", "your_client_secret"))
)
```

```python
from keycardai.mcp.integrations.fastmcp import AuthProvider, WebIdentity

# Web Identity (Private Key JWT)
auth_provider = AuthProvider(
    zone_id="your-zone-id",
    mcp_server_name="My FastMCP Service",
    mcp_base_url="http://localhost:8000/",
    application_credential=WebIdentity(
        mcp_server_name="My FastMCP Service",
        storage_dir="./mcp_keys"  # Directory for key storage
    )
)
```

```python
from keycardai.mcp.integrations.fastmcp import AuthProvider, EKSWorkloadIdentity

# EKS Workload Identity
auth_provider = AuthProvider(
    zone_id="your-zone-id",
    mcp_server_name="My FastMCP Service",
    mcp_base_url="http://localhost:8000/",
    application_credential=EKSWorkloadIdentity()
)
```

##### 2. Environment Variable Discovery (Convenient for Development)

The SDK automatically discovers credentials from environment variables, making it easy to configure without code changes:

**Option A: Client Credentials**
```bash
export KEYCARD_CLIENT_ID="your_client_id"
export KEYCARD_CLIENT_SECRET="your_client_secret"
```

**Option B: Explicit Credential Type**
```bash
# For EKS Workload Identity
export KEYCARD_APPLICATION_CREDENTIAL_TYPE="eks_workload_identity"
# Optional: Custom token file path (defaults to AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE or AWS_WEB_IDENTITY_TOKEN_FILE)
export KEYCARD_EKS_WORKLOAD_IDENTITY_TOKEN_FILE="/var/run/secrets/eks.amazonaws.com/serviceaccount/token"

# For Web Identity
export KEYCARD_APPLICATION_CREDENTIAL_TYPE="web_identity"
export KEYCARD_WEB_IDENTITY_KEY_STORAGE_DIR="./mcp_keys"  # Optional: defaults to "./mcp_keys"
```

**Option C: Automatic EKS Detection**
```bash
# SDK automatically detects EKS when this environment variable is present
export AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE="/var/run/secrets/eks.amazonaws.com/serviceaccount/token"
```

With environment variables configured, you can create the `AuthProvider` without explicit credentials:

```python
from keycardai.mcp.integrations.fastmcp import AuthProvider

# Credentials automatically discovered from environment variables
auth_provider = AuthProvider(
    zone_id="your-zone-id",
    mcp_server_name="My FastMCP Service",
    mcp_base_url="http://localhost:8000/"
)
```

#### Configuration Precedence

When multiple configuration methods are present, the SDK follows this precedence order (highest to lowest):

1. **Explicit `application_credential` parameter** - Always takes priority
2. **`KEYCARD_CLIENT_ID` + `KEYCARD_CLIENT_SECRET`** - Client credentials via environment
3. **`KEYCARD_APPLICATION_CREDENTIAL_TYPE`** - Explicit credential type selection
4. **`AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`** - Automatic EKS detection
5. **None** - No credentials configured (token exchange disabled)

**Example:**
```python
# Even with environment variables set, explicit parameter takes priority
import os
os.environ["KEYCARD_CLIENT_ID"] = "env_client_id"
os.environ["KEYCARD_CLIENT_SECRET"] = "env_secret"

auth_provider = AuthProvider(
    zone_id="your-zone-id",
    mcp_server_name="My FastMCP Service",
    mcp_base_url="http://localhost:8000/",
    # This takes priority over environment variables
    application_credential=WebIdentity(mcp_server_name="My FastMCP Service")
)
```

#### Supported Credential Types via Environment Variables

| Environment Variable | Value | Resulting Credential Type |
|---------------------|-------|---------------------------|
| `KEYCARD_APPLICATION_CREDENTIAL_TYPE` | `"eks_workload_identity"` | `EKSWorkloadIdentity` |
| `KEYCARD_APPLICATION_CREDENTIAL_TYPE` | `"web_identity"` | `WebIdentity` |
| `KEYCARD_APPLICATION_CREDENTIAL_TYPE` | `"unknown_type"` | ❌ Raises `AuthProviderConfigurationError` |

#### Additional Environment Variables

| Environment Variable | Purpose | Used By | Default Value |
|---------------------|---------|---------|---------------|
| `KEYCARD_CLIENT_ID` | OAuth client identifier | `ClientSecret` | None |
| `KEYCARD_CLIENT_SECRET` | OAuth client secret | `ClientSecret` | None |
| `KEYCARD_APPLICATION_CREDENTIAL_TYPE` | Explicit credential type selection | All | None |
| `KEYCARD_WEB_IDENTITY_KEY_STORAGE_DIR` | Directory for private key storage | `WebIdentity` | `"./mcp_keys"` |
| `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` | Path to EKS token file | `EKSWorkloadIdentity` | None |

#### Running Without Application Credentials

If no application credentials are configured, the `AuthProvider` will work for basic authentication but the `@grant` decorator will be unable to perform token exchange. This is useful for MCP servers that only need user authentication without delegated access to external resources.

## Testing

This section provides comprehensive guidance on testing your FastMCP servers that use Keycard authentication. The examples show how to use the `mock_access_context` utility to easily mock authentication without needing to understand the internal SDK implementation.

### Overview

When testing FastMCP servers with Keycard authentication, you need to mock the authentication system. The `mock_access_context` utility provides four main testing scenarios:

1. **Default token** - Always returns a default access token for any resource
2. **Custom token** - Returns a specific access token for any resource  
3. **Resource-specific tokens** - Returns different tokens for different resources
4. **Error scenarios** - Simulates authentication failures

### Basic Test Setup

### Testing Tools With Grant Decorators

For tools that use the `@grant` decorator, use the `mock_access_context` utility to mock the authentication system:

#### 1. Default Token (Simple Case)

```python
@pytest.mark.asyncio
async def test_tool_with_default_token(auth_provider):
    """Test a tool with default access token."""
    
    # Create FastMCP server
    mcp = FastMCP("Test Server", auth=auth_provider.get_remote_auth_provider())
    
    @mcp.tool()
    @auth_provider.grant("https://api.example.com")
    def call_external_api(ctx: Context, query: str) -> str:
        access_context = ctx.get_state("keycardai")
        
        if access_context.has_errors():
            return f"Error: {access_context.get_errors()}"
        
        token = access_context.access("https://api.example.com").access_token
        return f"API result for {query} with token {token}"
    
    # Test with default token
    with mock_access_context():  # Uses "test_access_token" by default
        async with Client(mcp) as client:
            result = await client.call_tool("call_external_api", {"query": "test"})
    
    assert result is not None
    assert "test_access_token" in result.data
    assert "API result for test" in result.data
```

#### 2. Custom Token

```python
@pytest.mark.asyncio
async def test_tool_with_custom_token(auth_provider):
    """Test a tool with a specific access token."""
    
    mcp = FastMCP("Test Server", auth=auth_provider.get_remote_auth_provider())
    
    @mcp.tool()
    @auth_provider.grant("https://api.example.com")
    def call_external_api(ctx: Context, query: str) -> str:
        access_context = ctx.get_state("keycardai")
        token = access_context.access("https://api.example.com").access_token
        return f"API result for {query} with token {token}"
    
    # Test with custom token
    with mock_access_context(access_token="my_custom_token_123"):
        async with Client(mcp) as client:
            result = await client.call_tool("call_external_api", {"query": "test"})
    
    assert "my_custom_token_123" in result.data
```

#### 3. Resource-Specific Tokens

```python
@pytest.mark.asyncio
async def test_tool_with_resource_specific_tokens(auth_provider):
    """Test a tool with different tokens for different resources."""
    
    mcp = FastMCP("Test Server", auth=auth_provider.get_remote_auth_provider())
    
    @mcp.tool()
    @auth_provider.grant(["https://api.example.com", "https://calendar-api.com"])
    def sync_data(ctx: Context) -> str:
        access_context = ctx.get_state("keycardai")
        
        api_token = access_context.access("https://api.example.com").access_token
        calendar_token = access_context.access("https://calendar-api.com").access_token
        
        return f"API: {api_token}, Calendar: {calendar_token}"
    
    # Test with resource-specific tokens
    with mock_access_context(resource_tokens={
        "https://api.example.com": "api_token_123",
        "https://calendar-api.com": "calendar_token_456"
    }):
        async with Client(mcp) as client:
            result = await client.call_tool("sync_data", {})
    
    assert "api_token_123" in result.data
    assert "calendar_token_456" in result.data
```

### Testing Error Scenarios

Test how your tools handle authentication errors using the `has_errors` parameter:

```python
@pytest.mark.asyncio
async def test_tool_with_authentication_error(auth_provider):
    """Test tool behavior when authentication fails."""
    
    mcp = FastMCP("Test Server", auth=auth_provider.get_remote_auth_provider())
    
    @mcp.tool()
    @auth_provider.grant("https://api.example.com")
    def failing_tool(ctx: Context, query: str) -> str:
        access_context = ctx.get_state("keycardai")
        
        # Always check for errors first
        if access_context.has_errors():
            return f"Authentication failed: {access_context.get_errors()}"
        
        token = access_context.access("https://api.example.com").access_token
        return f"Success: {query}"
    
    # Test with authentication error
    with mock_access_context(has_errors=True, error_message="Token exchange failed"):
        async with Client(mcp) as client:
            result = await client.call_tool("failing_tool", {"query": "test"})
    
    assert result is not None
    assert "Authentication failed" in result.data
    assert "Token exchange failed" in result.data

@pytest.mark.asyncio
async def test_tool_with_custom_error_message(auth_provider):
    """Test tool with custom error message."""
    
    mcp = FastMCP("Test Server", auth=auth_provider.get_remote_auth_provider())
    
    @mcp.tool()
    @auth_provider.grant("https://api.example.com")
    def error_handling_tool(ctx: Context) -> str:
        access_context = ctx.get_state("keycardai")
        
        if access_context.has_errors():
            return f"Error occurred: {access_context.get_errors()}"
        
        return "Success"
    
    # Test with custom error message
    with mock_access_context(has_errors=True, error_message="Custom auth error"):
        async with Client(mcp) as client:
            result = await client.call_tool("error_handling_tool", {})
    
    assert "Custom auth error" in result.data
```

## Troubleshooting

### [Cursor](https://cursor.com/home) Configuration Issues

#### Common Error: HTTP 404 with "Not Found" Response

**Symptoms:**
- Cursor shows error logs like: `HTTP 404: Invalid OAuth error response: SyntaxError: Unexpected token 'N', "Not Found" is not valid JSON. Raw body: Not Found`
- Server logs show multiple 404 errors for various OAuth discovery endpoints

**Root Cause:**
This error occurs when the `mcp_base_url` in your Keycard configuration doesn't match the actual URL where your FastMCP server is running. The FastMCP server currently only supports the OAuth authorization server discovery endpoint, but Cursor attempts to discover multiple OAuth endpoints.

**Server-side logs you might see:**
```
INFO: 192.168.1.64:52715 - "POST /mcp HTTP/1.1" 401 Unauthorized
INFO: 192.168.1.64:52716 - "GET /mcp/.well-known/oauth-protected-resource HTTP/1.1" 404 Not Found
INFO: 192.168.1.64:52717 - "GET /.well-known/oauth-authorization-server/mcp HTTP/1.1" 404 Not Found
INFO: 192.168.1.64:52718 - "GET /.well-known/oauth-authorization-server HTTP/1.1" 404 Not Found
INFO: 192.168.1.64:52719 - "GET /.well-known/openid-configuration/mcp HTTP/1.1" 404 Not Found
INFO: 192.168.1.64:52720 - "GET /mcp/.well-known/openid-configuration HTTP/1.1" 404 Not Found
```

**Solution:**

1. **Verify your FastMCP server URL**: Ensure your FastMCP server is running on the exact URL you configured in Keycard
2. **Check the trailing slash**: The `mcp_base_url` should match exactly what's configured in your Keycard resource settings
3. **Test the OAuth discovery endpoint**: Verify that `http://your-server-url/.well-known/oauth-authorization-server` returns a valid JSON response.

**Example Configuration:**

```python
# If your server runs on http://localhost:8000
auth_provider = AuthProvider(
    zone_id="your-zone-id",
    mcp_server_name="My FastMCP Server",
    mcp_base_url="http://localhost:8000"  # This will become "http://localhost:8000/" internally
)

# Your Keycard Resource must be configured as: http://localhost:8000/
```

**Testing the Configuration:**

1. Start your FastMCP server
2. Test the OAuth discovery endpoint:
   ```bash
   curl http://localhost:8000/.well-known/oauth-authorization-server
   ```
   This should return a JSON response with OAuth server metadata.

3. If you get a 404, check that:
   - Your server is running on the correct port
   - The URL in your Keycard resource settings matches exactly
   - You're using the correct protocol (http vs https)

**Important URL Configuration Note:**

There's a key difference in how URLs are configured between Keycard and Cursor:

- **Keycard Resource Configuration**: Use the base URL without the `/mcp` suffix
  - ✅ Correct: `http://localhost:8000/`
  - ❌ Incorrect: `http://localhost:8000/mcp`

- **Cursor MCP Server Configuration**: Include the `/mcp` suffix in the server URL
  - ✅ Correct: `http://localhost:8000/mcp`
  - ❌ Incorrect: `http://localhost:8000/`

This is because FastMCP automatically appends the `/mcp` path to your base URL for the MCP protocol endpoints, while Cursor needs to connect directly to the MCP endpoint.

## Examples

For complete examples and advanced usage patterns, see our [documentation](https://docs.keycard.ai).

## License

MIT License - see [LICENSE](https://github.com/keycardai/python-sdk/blob/main/LICENSE) file for details.

## Support

- 📖 [Documentation](https://docs.keycard.ai)
- 🐛 [Issue Tracker](https://github.com/keycardai/python-sdk/issues)
- 📧 [Support Email](mailto:support@keycard.ai)
