Keycard handles OAuth, identity, and access so your MCP servers don't have to. Add authentication, authorization, and delegated API access to any MCP server with a few lines of Python — no token plumbing, no auth middleware, no security footguns.
- Drop-in auth for MCP servers (OAuth 2.0, PKCE, token exchange — handled for you)
- Delegated access — call Google, GitHub, Slack APIs on behalf of your users with automatic token exchange
- Works with both the MCP Python SDK and the FastMCP framework
| You want to... | Install | Guide |
|---|---|---|
Add auth to MCP servers (using the mcp SDK) | pip install keycardai-mcp | Quick Start |
| Add auth to FastMCP servers | pip install keycardai-fastmcp | Quick Start |
| Connect to MCP servers as a client | pip install keycardai-mcp | MCP Client docs |
| Build agent-to-agent (A2A) services | pip install keycardai-a2a | A2A docs |
| Use the OAuth 2.0 client directly | pip install keycardai-oauth | OAuth docs |
- Zone — A Keycard environment that groups your identity providers, MCP resources, and access policies. Get your zone ID from console.keycard.ai.
- Delegated Access — Calling external APIs (Google, GitHub, Slack, etc.) on behalf of your authenticated users via RFC 8693 token exchange.
@grantdecorator — Declares which external APIs a tool needs. Automatically exchanges the user's token for a scoped token before your function runs.- AccessContext — The result of a grant. Contains exchanged tokens or errors. Non-throwing by design — always check
.has_errors()before using tokens. - Application Credentials — How your server authenticates with Keycard for token exchange. Three types:
ClientSecret,WebIdentity,EKSWorkloadIdentity.
- FastMCP 3.x Required: The
keycardai-fastmcppackage requires FastMCP 3.0 or later. FastMCP 3.0 madectx.get_state()andctx.set_state()async; all tool functions using these calls must beasync def. - MCP Protocol Version: Tested against MCP protocol version as implemented by
mcp>=1.13.1. Newer MCP protocol versions may introduce incompatibilities.
- Standalone Identity Provider: Keycard SDKs are designed to integrate with Keycard's hosted identity service, not to provide standalone identity management.
- Multi-Language Support: This SDK is Python-only. Other language SDKs are separate projects.
- Offline Operation: All authentication flows require network connectivity to Keycard services.
| Python Version | Status |
|---|---|
| 3.9 | Not Supported |
| 3.10 | Supported (minimum) |
| 3.11 | Supported |
| 3.12 | Supported |
| 3.13 | Supported |
| Package | Dependency | Version Constraint | Rationale |
|---|---|---|---|
keycardai-fastmcp | fastmcp | >=3.0.0 | FastMCP 3.0+ required. ctx.get_state()/ctx.set_state() are now async. |
| All packages | pydantic | >=2.11.7 | No upper bound - Pydantic 2.x maintains backward compatibility. |
| All packages | httpx | >=0.27.2 | No upper bound - httpx follows semver. |
keycardai-mcp | mcp | >=1.13.1 | No upper bound - API is protocol-defined. |
Following Python packaging best practices:
- Upper bounds cause resolver conflicts in end-user projects when multiple packages specify conflicting ranges.
- Well-maintained libraries (pydantic, httpx) follow semantic versioning and maintain backward compatibility.
- Testing against latest via CI catches issues before users encounter them.
All packages follow Semantic Versioning:
- MAJOR.MINOR.PATCH (e.g.,
0.15.0) - During
0.x.ydevelopment:- MINOR bumps (
0.x.0) may contain breaking changes - PATCH bumps (
0.x.y) are backward-compatible bug fixes
- MINOR bumps (
Packages will graduate to 1.0.0 when:
- Public API is stable and well-documented
- Comprehensive test coverage exists
- Production usage validates the design
- No planned breaking changes for foreseeable future
- Breaking changes are documented in CHANGELOG.md with migration guides
- Deprecation warnings will be added before removal where feasible
- Commit messages use
!suffix (e.g.,feat!:) for breaking changes - Release notes highlight breaking changes prominently
mcpvsfastmcp: ThemcpSDK includes a built-inFastMCPclass (from mcp.server.fastmcp import FastMCP), whilefastmcpis a separate standalone framework (from fastmcp import FastMCP). They're different libraries.keycardai-mcpwraps the former;keycardai-fastmcpwraps the latter.
- Python 3.10+ and a virtual environment
- Sign up at keycard.ai and get your zone ID from Zone Settings
- Configure an identity provider (Google, Microsoft, etc.) and create an MCP resource in your zone
uv add keycardai-fastmcp fastmcpfromfastmcpimportFastMCPfromkeycardai.fastmcpimportAuthProvider# Configure Keycard authenticationauth_provider=AuthProvider(
zone_id="your-zone-id", # From console.keycard.aimcp_server_name="My Server",
mcp_base_url="http://localhost:8000/"
)
# Create authenticated MCP serverauth=auth_provider.get_remote_auth_provider()
mcp=FastMCP("My Server", auth=auth)
@mcp.tool()defhello_world(name: str) ->str:
"""Say hello to someone."""returnf"Hello, {name}!"if__name__=="__main__":
mcp.run(transport="streamable-http")See the FastMCP examples for runnable projects.
pip install keycardai-mcp uvicornfrommcp.server.fastmcpimportFastMCPfromkeycardai.mcp.server.authimportAuthProviderimportuvicorn# Your MCP servermcp=FastMCP("My Server")
@mcp.tool()defhello_world(name: str) ->str:
"""Say hello to someone."""returnf"Hello, {name}!"# Add Keycard authenticationauth_provider=AuthProvider(
zone_id="your-zone-id", # From console.keycard.aimcp_server_name="My Server",
mcp_server_url="http://localhost:8000/"
)
# Wrap with auth and runapp=auth_provider.app(mcp)
uvicorn.run(app, host="0.0.0.0", port=8000)See the MCP examples for runnable projects.
Delegated access lets your MCP tools call external APIs (Google Calendar, GitHub, Slack, etc.) on behalf of authenticated users via automatic token exchange.
Setup: Get client credentials from console.keycard.ai, then set KEYCARD_CLIENT_ID and KEYCARD_CLIENT_SECRET as environment variables.
importosimporthttpxfromfastmcpimportFastMCP, Contextfromkeycardai.fastmcpimportAuthProvider, AccessContext, ClientSecretauth_provider=AuthProvider(
zone_id="your-zone-id",
mcp_server_name="My Server",
mcp_base_url="http://localhost:8000/",
application_credential=ClientSecret((
os.getenv("KEYCARD_CLIENT_ID"),
os.getenv("KEYCARD_CLIENT_SECRET")
))
)
auth=auth_provider.get_remote_auth_provider()
mcp=FastMCP("My Server", auth=auth)
@mcp.tool()@auth_provider.grant("https://www.googleapis.com/calendar/v3")asyncdefget_calendar_events(ctx: Context) ->dict:
"""Get the user's calendar events with delegated access."""# Retrieve access context from FastMCP contextaccess_context: AccessContext=awaitctx.get_state("keycardai")
ifaccess_context.has_errors():
return {"error": f"Token exchange failed: {access_context.get_errors()}"}
token=access_context.access("https://www.googleapis.com/calendar/v3").access_tokenasyncwithhttpx.AsyncClient() asclient:
response=awaitclient.get(
"https://www.googleapis.com/calendar/v3/calendars/primary/events",
headers={"Authorization": f"Bearer {token}"}
)
response.raise_for_status()
returnresponse.json()importosimporthttpxfrommcp.server.fastmcpimportFastMCP, Contextfromkeycardai.mcp.server.authimportAuthProvider, AccessContext, ClientSecretauth_provider=AuthProvider(
zone_id="your-zone-id",
mcp_server_name="My Server",
mcp_server_url="http://localhost:8000/",
application_credential=ClientSecret((
os.getenv("KEYCARD_CLIENT_ID"),
os.getenv("KEYCARD_CLIENT_SECRET")
))
)
mcp=FastMCP("My Server")
@mcp.tool()@auth_provider.grant("https://www.googleapis.com/calendar/v3")asyncdefget_calendar_events(access_ctx: AccessContext, ctx: Context) ->dict:
"""Get the user's calendar events with delegated access."""# @grant requires both AccessContext (for tokens) and Context (for request state)ifaccess_ctx.has_errors():
return {"error": f"Token exchange failed: {access_ctx.get_errors()}"}
token=access_ctx.access("https://www.googleapis.com/calendar/v3").access_tokenasyncwithhttpx.AsyncClient() asclient:
response=awaitclient.get(
"https://www.googleapis.com/calendar/v3/calendars/primary/events",
headers={"Authorization": f"Bearer {token}"}
)
response.raise_for_status()
returnresponse.json()
app=auth_provider.app(mcp)Key difference: In
keycardai-mcp, the@grantdecorator requires bothaccess_ctx: AccessContextandctx: Contextas function parameters. Inkeycardai-fastmcp,AccessContextis retrieved from the FastMCPContextviaawait ctx.get_state("keycardai").
For complete delegated access examples with error handling patterns, see:
Configure the remote MCP in your AI client (e.g., Cursor):
{
"mcpServers": {
"my-server": {
"url": "http://localhost:8000/mcp"
}
}
}Mounting a FastMCP server into a larger FastAPI service introduces a few gotchas, particularly related to the various OAuth metadata endpoints.
Note
Most MCP clients expect standards-compliance. Follow this approach if you're using those clients or the official MCP SDKs.
The OAuth spec declares that your metadata must be exposed at the root of your service.
/.well-known/oauth-protected-resource
This causes a problem when you're mounting multiple APIs or MCP servers to a common FastAPI service. Each API or MCP Server will potentially have their own OAuth metadata.
The OAuth spec defines that the metadata for each individual service should be
exposed as an extension to the base well-known URI. For example:
/.well-known/oauth-protected-resource/api
/.well-known/oauth-protected-resource/mcp-server/mcp
To ensure FastMCP and FastAPI produce this, you need to ensure your routing is defined in a specific way:
fromfastmcpimportFastMCPfromfastapiimportFastAPImcp=FastMCP("MCP Server")
mcp_app=mcp.http_app() # DO NOT specify a path hereapp=FastAPI(title="API", lifespan=mcp_app.lifespan)
# You MUST mount the MCP's `http_app` to the full path for FastMCP to expose the# OAuth metadata correctly.app.mount("/mcp-server/mcp", mcp_app)Warning
This is not advised. Only follow this if you know for sure you need flexibility outside of what the spec requires.
If you've built custom clients or need to mount the metadata at a different, non standards compliant, location, you can do that manually.
fromfastmcpimportFastMCPfromfastapiimportFastAPIfromkeycardai.mcp.server.routers.metadataimportwell_known_metadata_mountauth_provider=AuthProvider(
zone_id="your-zone-id",
mcp_server_name="My Server",
mcp_base_url="http://127.0.0.1:8000/"
)
auth=auth_provider.get_remote_auth_provider()
mcp=FastMCP("MCP Server", auth=auth)
mcp_app=mcp.http_app()
app=FastAPI(title="API", lifespan=mcp_app.lifespan)
app.mount(
"/custom-well-known",
well_known_metadata_mount(issuer=auth.zone_url),
)which will produce the following endpoints
/custom-well-known/oauth-protected-resource
/custom-well-known/oauth-authorization-server
If you need even more control, you can mount the individual routes at a specific URI.
fromfastmcpimportFastMCPfromfastapiimportFastAPIfromkeycardai.mcp.server.routers.metadataimport (
well_known_authorization_server_route,
well_known_protected_resource_route,
)
auth_provider=AuthProvider(
zone_id="your-zone-id",
mcp_server_name="My Server",
mcp_base_url="http://127.0.0.1:8000/"
)
auth=auth_provider.get_remote_auth_provider()
mcp=FastMCP("MCP Server", auth=auth)
mcp_app=mcp.http_app()
app=FastAPI(title="API", lifespan=mcp_app.lifespan)
app.router.routes.append(
well_known_protected_resource_route(
path="/my/custom/path/to/well-known/oauth-protected-resource",
issuer=auth.zone_url,
)
)
app.router.routes.append(
well_known_authorization_server_route(
path="/my/custom/path/to/well-known/oauth-authorization-server",
issuer=auth.zone_url,
)
)which will produce the following endpoints
/my/custom/path/to/well-known/oauth-protected-resource
/my/custom/path/to/well-known/oauth-authorization-server
When testing your MCP server with the modelcontextprotocol/inspector, you may need to configure CORS to allow the inspector's web interface to access your protected endpoints from localhost.
Note: This applies specifically to keycardai-mcp. When using keycardai-fastmcp, no middleware is currently required as FastMCP permits access to metadata endpoints by default.
fromstarlette.middlewareimportMiddlewarefromstarlette.middleware.corsimportCORSMiddlewaremiddleware= [
Middleware(
CORSMiddleware,
allow_origins=["*"], # For local dev onlyallow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
]
app=auth_provider.app(mcp, middleware=middleware)Important: The allow_origins=["*"] setting is for local development only. In production, restrict to specific domains.
- Full documentation — API reference, tutorials, integration guides
- Package docs:
- keycardai-mcp — MCP server authentication
- keycardai-fastmcp — FastMCP integration
- keycardai-mcp client — MCP client (CLI, web apps, AI agent integrations)
- keycardai-a2a — Agent-to-agent delegation (A2A)
- keycardai-oauth — OAuth 2.0 client
- Examples:MCP · FastMCP · OAuth · A2A
This project is licensed under the MIT License - see the LICENSE file for details.
- GitHub Issues: https://github.com/keycardai/python-sdk/issues
- Documentation: https://docs.keycard.ai
- Email: support@keycard.ai