keycardai-mcp-fastmcp


Namekeycardai-mcp-fastmcp JSON
Version 0.12.0 PyPI version JSON
download
home_pageNone
SummaryFastMCP integration for Keycard OAuth client with automated token exchange and authentication
upload_time2025-10-29 21:46:12
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseMIT
keywords authentication fastmcp keycard mcp model-context-protocol oauth token-exchange
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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/
```

### Client Credentials for Token Exchange

To enable token exchange (required for the `@grant` decorator), provide application credentials:

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

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"))
)
```

## 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)

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "keycardai-mcp-fastmcp",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "authentication, fastmcp, keycard, mcp, model-context-protocol, oauth, token-exchange",
    "author": null,
    "author_email": "Keycard <support@keycard.ai>",
    "download_url": "https://files.pythonhosted.org/packages/8f/13/60e1beaf48a348b1d8f92c19da2c7e454b45ac184c7581b673060b31a735/keycardai_mcp_fastmcp-0.12.0.tar.gz",
    "platform": null,
    "description": "# Keycard FastMCP Integration\n\nA Python package that provides seamless integration between Keycard and FastMCP servers, enabling secure token exchange and authentication for MCP tools.\n\n## Requirements\n\n- **Python 3.9 or greater**\n- Virtual environment (recommended)\n\n## Setup Guide\n\n### Option 1: Using uv (Recommended)\n\nIf you have [uv](https://docs.astral.sh/uv/) installed:\n\n```bash\n# Create a new project with uv\nuv init my-fastmcp-project\ncd my-fastmcp-project\n\n# Create and activate virtual environment\nuv venv\nsource .venv/bin/activate  # On Windows: .venv\\Scripts\\activate\n```\n\n### Option 2: Using Standard Python\n\n```bash\n# Create project directory\nmkdir my-fastmcp-project\ncd my-fastmcp-project\n\n# Create and activate virtual environment\npython3 -m venv .venv\nsource .venv/bin/activate  # On Windows: .venv\\Scripts\\activate\n\n# Upgrade pip (recommended)\npip install --upgrade pip\n```\n\n## Installation\n\n```bash\nuv add keycardai-mcp-fastmcp\n```\n\nor\n\n```bash\npip install keycardai-mcp-fastmcp\n```\n\n## Quick Start\n\nAdd Keycard authentication to your existing FastMCP server:\n\n### Install the Package\n\n```bash\nuv add keycardai-mcp-fastmcp\n```\n\n### Get Your Keycard Zone ID\n\n1. Sign up at [keycard.ai](https://keycard.ai)\n2. Navigate to Zone Settings to get your zone ID\n3. Configure your preferred identity provider (Google, Microsoft, etc.)\n4. Create an MCP resource in your zone\n\n### Add Authentication to Your FastMCP Server\n\n```python\nfrom fastmcp import FastMCP, Context\nfrom keycardai.mcp.integrations.fastmcp import AuthProvider\n\n# Configure Keycard authentication (recommended: use zone_id)\nauth_provider = AuthProvider(\n    zone_id=\"your-zone-id\",  # Get this from keycard.ai\n    mcp_server_name=\"My Secure FastMCP Server\",\n    mcp_base_url=\"http://127.0.0.1:8000/\"  # Note: trailing slash will be added automatically\n)\n\n# Get the RemoteAuthProvider for FastMCP\nauth = auth_provider.get_remote_auth_provider()\n\n# Create authenticated FastMCP server\nmcp = FastMCP(\"My Secure FastMCP Server\", auth=auth)\n\n@mcp.tool()\ndef hello_world(name: str) -> str:\n    return f\"Hello, {name}!\"\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"streamable-http\")\n```\n\n### Add access delegation to tool calls\n\n```python\nfrom fastmcp import FastMCP, Context\nfrom keycardai.mcp.integrations.fastmcp import AuthProvider, AccessContext\n\n# Configure Keycard authentication (recommended: use zone_id)\nauth_provider = AuthProvider(\n    zone_id=\"your-zone-id\",  # Get this from keycard.ai\n    mcp_server_name=\"My Secure FastMCP Server\",\n    mcp_base_url=\"http://127.0.0.1:8000/\"  # Note: trailing slash will be added automatically\n)\n\n# Get the RemoteAuthProvider for FastMCP\nauth = auth_provider.get_remote_auth_provider()\n\n# Create authenticated FastMCP server\nmcp = FastMCP(\"My Secure FastMCP Server\", auth=auth)\n\n# Example with token exchange for external API access\n@mcp.tool()\n@auth_provider.grant(\"https://api.example.com\")\ndef call_external_api(ctx: Context, query: str) -> str:\n    # Get access context to check token exchange status\n    access_context: AccessContext = ctx.get_state(\"keycardai\")\n    \n    # Check for errors before accessing token\n    if access_context.has_errors():\n        return f\"Error: Failed to obtain access token - {access_context.get_errors()}\"\n    \n    # Access delegated token through context namespace\n    token = access_context.access(\"https://api.example.com\").access_token\n    # Use token to call external API\n    return f\"Results for {query}\"\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"streamable-http\")\n```\n\n### \ud83c\udf89 Your FastMCP server is now protected with Keycard authentication! \ud83c\udf89\n\n## Working with AccessContext\n\nWhen 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.\n\nThe `@grant()` decorator avoids raising exceptions. Instead, it exposes error information via associated metadata. \nYou can check if the context encountered errors by calling the `has_errors()` method.\n\n### Basic Usage\n\n```python\nfrom keycardai.mcp.integrations.fastmcp import AccessContext\n\n@mcp.tool()\n@auth_provider.grant(\"https://api.example.com\")\ndef my_tool(ctx: Context, user_id: str) -> str:\n    # Get the access context\n    access_context: AccessContext = ctx.get_state(\"keycardai\")\n    \n    # Always check for errors first\n    if access_context.has_errors():\n        # Handle the error case\n        errors = access_context.get_errors()\n        return f\"Authentication failed: {errors}\"\n    \n    # Access the token for the specific resource\n    token = access_context.access(\"https://api.example.com\").access_token\n    \n    # Use the token in your API calls\n    headers = {\"Authorization\": f\"Bearer {token}\"}\n    # Make your API request...\n    return f\"Success for user {user_id}\"\n```\n\n### Multiple Resources\n\nYou can request tokens for multiple resources in a single decorator:\n\n```python\n@mcp.tool()\n@auth_provider.grant([\"https://api.example.com\", \"https://other-api.com\"])\ndef multi_resource_tool(ctx: Context) -> str:\n    access_context: AccessContext = ctx.get_state(\"keycardai\")\n    \n    # Check overall status\n    status = access_context.get_status()  # \"success\", \"partial_error\", or \"error\"\n    \n    if status == \"error\":\n        # Global error - no tokens available\n        return f\"Global error: {access_context.get_error()}\"\n    \n    elif status == \"partial_error\":\n        # Some resources succeeded, others failed\n        successful = access_context.get_successful_resources()\n        failed = access_context.get_failed_resources()\n        \n        # Work with successful resources only\n        for resource in successful:\n            token = access_context.access(resource).access_token\n            # Use token...\n        \n        return f\"Partial success: {len(successful)} succeeded, {len(failed)} failed\"\n    \n    else:  # status == \"success\"\n        # All resources succeeded\n        token1 = access_context.access(\"https://api.example.com\").access_token\n        token2 = access_context.access(\"https://other-api.com\").access_token\n        # Use both tokens...\n        return \"All resources accessed successfully\"\n```\n\n### Error Handling Methods\n\nThe `AccessContext` provides several methods for checking errors:\n\n```python\n# Check if there are any errors (global or resource-specific)\nif access_context.has_errors():\n    # Handle any error case\n\n# Check for global errors only\nif access_context.has_error():\n    global_error = access_context.get_error()\n\n# Check for specific resource errors\nif access_context.has_resource_error(\"https://api.example.com\"):\n    resource_error = access_context.get_resource_errors(\"https://api.example.com\")\n\n# Get all errors (global + resource-specific)\nall_errors = access_context.get_errors()\n\n# Get status summary\nstatus = access_context.get_status()  # \"success\", \"partial_error\", or \"error\"\n\n# Get lists of successful/failed resources\nsuccessful_resources = access_context.get_successful_resources()\nfailed_resources = access_context.get_failed_resources()\n```\n\n## Important Configuration Notes\n\n### URL Slash Requirement\n\n\u26a0\ufe0f **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.\n\n**When configuring your Keycard Resource**, ensure the resource URL in your Keycard zone settings matches exactly, including the trailing slash:\n\n```python\n# This configuration...\nauth_provider = AuthProvider(\n    zone_id=\"your-zone-id\",\n    mcp_base_url=\"http://localhost:8000\"  # No trailing slash\n)\n\n# Will become \"http://localhost:8000/\" internally\n# So your Keycard Resource must be configured as: http://localhost:8000/\n```\n\n### Client Credentials for Token Exchange\n\nTo enable token exchange (required for the `@grant` decorator), provide application credentials:\n\n```python\nfrom keycardai.mcp.integrations.fastmcp import ClientSecret\n\nauth_provider = AuthProvider(\n    zone_id=\"your-zone-id\",\n    mcp_server_name=\"My FastMCP Service\",\n    mcp_base_url=\"http://localhost:8000/\",\n    application_credential=ClientSecret((\"your_client_id\", \"your_client_secret\"))\n)\n```\n\n## Testing\n\nThis 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.\n\n### Overview\n\nWhen testing FastMCP servers with Keycard authentication, you need to mock the authentication system. The `mock_access_context` utility provides four main testing scenarios:\n\n1. **Default token** - Always returns a default access token for any resource\n2. **Custom token** - Returns a specific access token for any resource  \n3. **Resource-specific tokens** - Returns different tokens for different resources\n4. **Error scenarios** - Simulates authentication failures\n\n### Basic Test Setup\n\n### Testing Tools With Grant Decorators\n\nFor tools that use the `@grant` decorator, use the `mock_access_context` utility to mock the authentication system:\n\n#### 1. Default Token (Simple Case)\n\n```python\n@pytest.mark.asyncio\nasync def test_tool_with_default_token(auth_provider):\n    \"\"\"Test a tool with default access token.\"\"\"\n    \n    # Create FastMCP server\n    mcp = FastMCP(\"Test Server\", auth=auth_provider.get_remote_auth_provider())\n    \n    @mcp.tool()\n    @auth_provider.grant(\"https://api.example.com\")\n    def call_external_api(ctx: Context, query: str) -> str:\n        access_context = ctx.get_state(\"keycardai\")\n        \n        if access_context.has_errors():\n            return f\"Error: {access_context.get_errors()}\"\n        \n        token = access_context.access(\"https://api.example.com\").access_token\n        return f\"API result for {query} with token {token}\"\n    \n    # Test with default token\n    with mock_access_context():  # Uses \"test_access_token\" by default\n        async with Client(mcp) as client:\n            result = await client.call_tool(\"call_external_api\", {\"query\": \"test\"})\n    \n    assert result is not None\n    assert \"test_access_token\" in result.data\n    assert \"API result for test\" in result.data\n```\n\n#### 2. Custom Token\n\n```python\n@pytest.mark.asyncio\nasync def test_tool_with_custom_token(auth_provider):\n    \"\"\"Test a tool with a specific access token.\"\"\"\n    \n    mcp = FastMCP(\"Test Server\", auth=auth_provider.get_remote_auth_provider())\n    \n    @mcp.tool()\n    @auth_provider.grant(\"https://api.example.com\")\n    def call_external_api(ctx: Context, query: str) -> str:\n        access_context = ctx.get_state(\"keycardai\")\n        token = access_context.access(\"https://api.example.com\").access_token\n        return f\"API result for {query} with token {token}\"\n    \n    # Test with custom token\n    with mock_access_context(access_token=\"my_custom_token_123\"):\n        async with Client(mcp) as client:\n            result = await client.call_tool(\"call_external_api\", {\"query\": \"test\"})\n    \n    assert \"my_custom_token_123\" in result.data\n```\n\n#### 3. Resource-Specific Tokens\n\n```python\n@pytest.mark.asyncio\nasync def test_tool_with_resource_specific_tokens(auth_provider):\n    \"\"\"Test a tool with different tokens for different resources.\"\"\"\n    \n    mcp = FastMCP(\"Test Server\", auth=auth_provider.get_remote_auth_provider())\n    \n    @mcp.tool()\n    @auth_provider.grant([\"https://api.example.com\", \"https://calendar-api.com\"])\n    def sync_data(ctx: Context) -> str:\n        access_context = ctx.get_state(\"keycardai\")\n        \n        api_token = access_context.access(\"https://api.example.com\").access_token\n        calendar_token = access_context.access(\"https://calendar-api.com\").access_token\n        \n        return f\"API: {api_token}, Calendar: {calendar_token}\"\n    \n    # Test with resource-specific tokens\n    with mock_access_context(resource_tokens={\n        \"https://api.example.com\": \"api_token_123\",\n        \"https://calendar-api.com\": \"calendar_token_456\"\n    }):\n        async with Client(mcp) as client:\n            result = await client.call_tool(\"sync_data\", {})\n    \n    assert \"api_token_123\" in result.data\n    assert \"calendar_token_456\" in result.data\n```\n\n### Testing Error Scenarios\n\nTest how your tools handle authentication errors using the `has_errors` parameter:\n\n```python\n@pytest.mark.asyncio\nasync def test_tool_with_authentication_error(auth_provider):\n    \"\"\"Test tool behavior when authentication fails.\"\"\"\n    \n    mcp = FastMCP(\"Test Server\", auth=auth_provider.get_remote_auth_provider())\n    \n    @mcp.tool()\n    @auth_provider.grant(\"https://api.example.com\")\n    def failing_tool(ctx: Context, query: str) -> str:\n        access_context = ctx.get_state(\"keycardai\")\n        \n        # Always check for errors first\n        if access_context.has_errors():\n            return f\"Authentication failed: {access_context.get_errors()}\"\n        \n        token = access_context.access(\"https://api.example.com\").access_token\n        return f\"Success: {query}\"\n    \n    # Test with authentication error\n    with mock_access_context(has_errors=True, error_message=\"Token exchange failed\"):\n        async with Client(mcp) as client:\n            result = await client.call_tool(\"failing_tool\", {\"query\": \"test\"})\n    \n    assert result is not None\n    assert \"Authentication failed\" in result.data\n    assert \"Token exchange failed\" in result.data\n\n@pytest.mark.asyncio\nasync def test_tool_with_custom_error_message(auth_provider):\n    \"\"\"Test tool with custom error message.\"\"\"\n    \n    mcp = FastMCP(\"Test Server\", auth=auth_provider.get_remote_auth_provider())\n    \n    @mcp.tool()\n    @auth_provider.grant(\"https://api.example.com\")\n    def error_handling_tool(ctx: Context) -> str:\n        access_context = ctx.get_state(\"keycardai\")\n        \n        if access_context.has_errors():\n            return f\"Error occurred: {access_context.get_errors()}\"\n        \n        return \"Success\"\n    \n    # Test with custom error message\n    with mock_access_context(has_errors=True, error_message=\"Custom auth error\"):\n        async with Client(mcp) as client:\n            result = await client.call_tool(\"error_handling_tool\", {})\n    \n    assert \"Custom auth error\" in result.data\n```\n\n## Troubleshooting\n\n### [Cursor](https://cursor.com/home) Configuration Issues\n\n#### Common Error: HTTP 404 with \"Not Found\" Response\n\n**Symptoms:**\n- 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`\n- Server logs show multiple 404 errors for various OAuth discovery endpoints\n\n**Root Cause:**\nThis 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.\n\n**Server-side logs you might see:**\n```\nINFO: 192.168.1.64:52715 - \"POST /mcp HTTP/1.1\" 401 Unauthorized\nINFO: 192.168.1.64:52716 - \"GET /mcp/.well-known/oauth-protected-resource HTTP/1.1\" 404 Not Found\nINFO: 192.168.1.64:52717 - \"GET /.well-known/oauth-authorization-server/mcp HTTP/1.1\" 404 Not Found\nINFO: 192.168.1.64:52718 - \"GET /.well-known/oauth-authorization-server HTTP/1.1\" 404 Not Found\nINFO: 192.168.1.64:52719 - \"GET /.well-known/openid-configuration/mcp HTTP/1.1\" 404 Not Found\nINFO: 192.168.1.64:52720 - \"GET /mcp/.well-known/openid-configuration HTTP/1.1\" 404 Not Found\n```\n\n**Solution:**\n\n1. **Verify your FastMCP server URL**: Ensure your FastMCP server is running on the exact URL you configured in Keycard\n2. **Check the trailing slash**: The `mcp_base_url` should match exactly what's configured in your Keycard resource settings\n3. **Test the OAuth discovery endpoint**: Verify that `http://your-server-url/.well-known/oauth-authorization-server` returns a valid JSON response.\n\n**Example Configuration:**\n\n```python\n# If your server runs on http://localhost:8000\nauth_provider = AuthProvider(\n    zone_id=\"your-zone-id\",\n    mcp_server_name=\"My FastMCP Server\",\n    mcp_base_url=\"http://localhost:8000\"  # This will become \"http://localhost:8000/\" internally\n)\n\n# Your Keycard Resource must be configured as: http://localhost:8000/\n```\n\n**Testing the Configuration:**\n\n1. Start your FastMCP server\n2. Test the OAuth discovery endpoint:\n   ```bash\n   curl http://localhost:8000/.well-known/oauth-authorization-server\n   ```\n   This should return a JSON response with OAuth server metadata.\n\n3. If you get a 404, check that:\n   - Your server is running on the correct port\n   - The URL in your Keycard resource settings matches exactly\n   - You're using the correct protocol (http vs https)\n\n**Important URL Configuration Note:**\n\nThere's a key difference in how URLs are configured between Keycard and Cursor:\n\n- **Keycard Resource Configuration**: Use the base URL without the `/mcp` suffix\n  - \u2705 Correct: `http://localhost:8000/`\n  - \u274c Incorrect: `http://localhost:8000/mcp`\n\n- **Cursor MCP Server Configuration**: Include the `/mcp` suffix in the server URL\n  - \u2705 Correct: `http://localhost:8000/mcp`\n  - \u274c Incorrect: `http://localhost:8000/`\n\nThis 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.\n\n## Examples\n\nFor complete examples and advanced usage patterns, see our [documentation](https://docs.keycard.ai).\n\n## License\n\nMIT License - see [LICENSE](https://github.com/keycardai/python-sdk/blob/main/LICENSE) file for details.\n\n## Support\n\n- \ud83d\udcd6 [Documentation](https://docs.keycard.ai)\n- \ud83d\udc1b [Issue Tracker](https://github.com/keycardai/python-sdk/issues)\n- \ud83d\udce7 [Support Email](mailto:support@keycard.ai)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "FastMCP integration for Keycard OAuth client with automated token exchange and authentication",
    "version": "0.12.0",
    "project_urls": {
        "Documentation": "https://docs.keycardai.com",
        "Homepage": "https://github.com/keycardai/python-sdk",
        "Issues": "https://github.com/keycardai/python-sdk/issues",
        "Repository": "https://github.com/keycardai/python-sdk"
    },
    "split_keywords": [
        "authentication",
        " fastmcp",
        " keycard",
        " mcp",
        " model-context-protocol",
        " oauth",
        " token-exchange"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "aec61fc8db74639febeef3ceb14fdd0211a8cf58649bc056ed0bbf0db27d9ec8",
                "md5": "ed86bb023ca0db8d530ee25b3eda921a",
                "sha256": "357e9cc08d335c09129b3845f766d07d83eff84de40d06a4a71fad795a2414d9"
            },
            "downloads": -1,
            "filename": "keycardai_mcp_fastmcp-0.12.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ed86bb023ca0db8d530ee25b3eda921a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 15776,
            "upload_time": "2025-10-29T21:46:10",
            "upload_time_iso_8601": "2025-10-29T21:46:10.822446Z",
            "url": "https://files.pythonhosted.org/packages/ae/c6/1fc8db74639febeef3ceb14fdd0211a8cf58649bc056ed0bbf0db27d9ec8/keycardai_mcp_fastmcp-0.12.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "8f1360e1beaf48a348b1d8f92c19da2c7e454b45ac184c7581b673060b31a735",
                "md5": "d0b4d6ac0e0d5aab1edcafe29bbf4f54",
                "sha256": "1bc47912eb8643eb957bbe8ce56e8ab27eb71784f78fb13273bd46be4bbdbefc"
            },
            "downloads": -1,
            "filename": "keycardai_mcp_fastmcp-0.12.0.tar.gz",
            "has_sig": false,
            "md5_digest": "d0b4d6ac0e0d5aab1edcafe29bbf4f54",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 21135,
            "upload_time": "2025-10-29T21:46:12",
            "upload_time_iso_8601": "2025-10-29T21:46:12.039583Z",
            "url": "https://files.pythonhosted.org/packages/8f/13/60e1beaf48a348b1d8f92c19da2c7e454b45ac184c7581b673060b31a735/keycardai_mcp_fastmcp-0.12.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-29 21:46:12",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "keycardai",
    "github_project": "python-sdk",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "keycardai-mcp-fastmcp"
}
        
Elapsed time: 1.62773s