diff --git a/.gitignore b/.gitignore index 55b9d7e..e96c3e3 100644 --- a/.gitignore +++ b/.gitignore @@ -43,3 +43,6 @@ data/ .Trashes ehthumbs.db Thumbs.db + + .cursor +CLAUDE.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6c468e4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,200 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (which shall not include communications that are reasonably + considered separate from, or merely peripheral to, the work). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based upon (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and derivative works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control + systems, and issue tracking systems that are managed by, or on behalf + of, the Licensor for the purpose of discussing and improving the Work, + but excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to use, reproduce, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Work, and to + permit persons to whom the Work is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Work. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, trademark, patent, + attribution and other notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright notice to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Support. You may choose to offer, and to + charge a fee for, warranty, support, indemnity or other liability + obligations and/or rights consistent with this License. However, in + accepting such obligations, You may act only on Your own behalf and on + Your sole responsibility, not on behalf of any other Contributor, and + only if You agree to indemnify, defend, and hold each Contributor + harmless for any liability incurred by, or claims asserted against, + such Contributor by reason of your accepting any such warranty or support. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in comments for the + particular programming language and file format. + + Copyright [2025] [Obot Platform] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index 414c7ce..a40fec8 100644 --- a/README.md +++ b/README.md @@ -1,510 +1,171 @@ # MCP OAuth Proxy -A comprehensive OAuth 2.1 proxy server implemented in Go that provides OAuth authorization server functionality with PostgreSQL storage. This proxy supports multiple OAuth providers (Google, Microsoft) and can proxy requests to MCP servers with user context headers. +MCP OAuth Proxy is an open-source OAuth 2.1 proxy server that adds authentication and authorization to MCP (Model Context Protocol) servers. -## Features +## What is MCP OAuth Proxy? -- **OAuth 2.1 Compliance**: Implements OAuth 2.1 best practices including short-lived access tokens, refresh token rotation, and token revocation -- **Multiple Provider Support**: Supports Google and Microsoft OAuth providers -- **PostgreSQL Storage**: Uses PostgreSQL for storing clients, grants, authorization codes, and tokens -- **JWT Token Management**: Generates and validates JWT tokens with embedded user properties -- **MCP Proxy**: Proxies requests to MCP servers with user context headers -- **CORS Support**: Configurable CORS headers for cross-origin requests -- **Rate Limiting**: Built-in rate limiting to prevent abuse -- **PKCE Support**: Supports PKCE (Proof Key for Code Exchange) for enhanced security +MCP OAuth Proxy acts as a bridge between OAuth providers (Google, Microsoft, GitHub) and MCP servers, providing: -## Architecture - -The OAuth proxy follows the Cloudflare Workers OAuth Provider pattern but is implemented in Go with database storage: - -- **Authorization Flow**: Clients request authorization, users approve, and authorization codes are generated -- **Token Exchange**: Authorization codes are exchanged for access and refresh tokens -- **Token Validation**: JWT tokens are validated and user properties are extracted -- **MCP Proxying**: Requests to MCP endpoints are proxied with user context headers - -## Database Support - -The proxy supports both PostgreSQL and SQLite databases: - -### PostgreSQL (Recommended for Production) - -- Full ACID compliance -- Better concurrent access -- Advanced features like JSONB for metadata storage -- Set `DATABASE_DSN="postgres://user:pass@host:port/dbname?sslmode=disable"` - -### SQLite (Default for Development) - -- Zero configuration -- Single file storage -- Perfect for development and small deployments -- Automatically used when `DATABASE_DSN` is not set -- Database file stored at `data/oauth_proxy.db` - -## Database Schema - -The proxy uses the following tables (compatible with both PostgreSQL and SQLite): - -- `clients`: OAuth client registrations -- `grants`: Authorization grants with user properties -- `authorization_codes`: Single-use authorization codes -- `access_tokens`: Access and refresh tokens with grant references - -## Configuration - -The application can be configured using environment variables: - -### Required Environment Variables - -- `SCOPES_SUPPORTED`: Comma-separated list of supported OAuth scopes (e.g., "openid,profile,email") -- `MCP_SERVER_URL`: URL of the MCP server to proxy requests to -- `OAUTH_CLIENT_ID`: OAuth client ID from your OAuth provider -- `OAUTH_CLIENT_SECRET`: OAuth client secret from your OAuth provider -- `OAUTH_AUTHORIZE_URL`: Authorization endpoint URL from your OAuth provider - -### Optional Environment Variables - -- `DATABASE_DSN`: Database connection string (PostgreSQL or SQLite). If not set, SQLite will be used with a local file at `data/oauth_proxy.db` -- `ENCRYPTION_KEY`: Base64-encoded 32-byte AES-256 key for encrypting sensitive data - -### Example Environment Variables - -```bash -# Example for Google OAuth with PostgreSQL -DATABASE_DSN="postgres://oauth_user:oauth_password@localhost:5432/oauth_proxy?sslmode=disable" -SCOPES_SUPPORTED="openid,profile,email" -OAUTH_CLIENT_ID="your-google-client-id.apps.googleusercontent.com" -OAUTH_CLIENT_SECRET="your-google-client-secret" -OAUTH_AUTHORIZE_URL="https://accounts.google.com" -MCP_SERVER_URL="http://localhost:3000" -ENCRYPTION_KEY="base64-encoded-32-byte-aes-256-key" - -# Example for Google OAuth with SQLite (DATABASE_DSN not set, will use data/oauth_proxy.db) -SCOPES_SUPPORTED="openid,profile,email" -OAUTH_CLIENT_ID="your-google-client-id.apps.googleusercontent.com" -OAUTH_CLIENT_SECRET="your-google-client-secret" -OAUTH_AUTHORIZE_URL="https://accounts.google.com" -MCP_SERVER_URL="http://localhost:3000" - -# Example for Microsoft Azure AD -# SCOPES_SUPPORTED="openid,profile,email,User.Read" -# OAUTH_AUTHORIZE_URL="https://login.microsoftonline.com/common/v2.0" - -# Example for GitHub -# SCOPES_SUPPORTED="read:user,user:email" -# OAUTH_AUTHORIZE_URL="https://github.com/login/oauth" -``` - -## OAuth Provider Setup - -### Google OAuth 2.0 - -1. **Create a Google Cloud Project**: - - - Go to [Google Cloud Console](https://console.cloud.google.com/) - - Create a new project or select an existing one - -2. **Enable OAuth 2.0 API**: - - - Go to "APIs & Services" > "Library" - - Search for "Google+ API" or "OAuth 2.0" and enable it - -3. **Create OAuth 2.0 Credentials**: - - - Go to "APIs & Services" > "Credentials" - - Click "Create Credentials" > "OAuth 2.0 Client IDs" - - Choose "Web application" as the application type - - Add authorized redirect URIs: `http://localhost:8080/callback` (for development) - - Note down the Client ID and Client Secret - -4. **Environment Variables**: - ```bash - OAUTH_CLIENT_ID="your-google-client-id.apps.googleusercontent.com" - OAUTH_CLIENT_SECRET="your-google-client-secret" - OAUTH_AUTHORIZE_URL="https://accounts.google.com" - SCOPES_SUPPORTED="openid,profile,email" - ``` - -### Microsoft Azure AD - -1. **Register an Application**: - - - Go to [Azure Portal](https://portal.azure.com/) - - Navigate to "Azure Active Directory" > "App registrations" - - Click "New registration" - - Enter a name for your application - - Set redirect URI to `http://localhost:8080/callback` (for development) - -2. **Configure Permissions**: - - - Go to "API permissions" - - Add "Microsoft Graph" > "Delegated permissions" - - Select: `User.Read`, `openid`, `profile`, `email` - - Click "Grant admin consent" - -3. **Get Client Credentials**: - - - Go to "Certificates & secrets" - - Create a new client secret - - Note down the Application (client) ID and the secret value - -4. **Environment Variables**: - ```bash - OAUTH_CLIENT_ID="your-azure-client-id" - OAUTH_CLIENT_SECRET="your-azure-client-secret" - OAUTH_AUTHORIZE_URL="https://login.microsoftonline.com/common/v2.0" - SCOPES_SUPPORTED="openid,profile,email,User.Read" - ``` - -### GitHub OAuth - -1. **Create a GitHub OAuth App**: - - - Go to [GitHub Settings](https://github.com/settings/developers) - - Click "New OAuth App" - - Fill in the application details: - - Application name: Your app name - - Homepage URL: `http://localhost:8080` (for development) - - Authorization callback URL: `http://localhost:8080/callback` - -2. **Get Client Credentials**: - - - After creating the app, you'll see the Client ID - - Click "Generate a new client secret" to get the Client Secret - -3. **Environment Variables**: - ```bash - OAUTH_CLIENT_ID="your-github-client-id" - OAUTH_CLIENT_SECRET="your-github-client-secret" - OAUTH_AUTHORIZE_URL="https://github.com/login/oauth" - SCOPES_SUPPORTED="read:user,user:email" - ``` - -### Redirect URI Configuration - -When configuring your OAuth provider, use these redirect URIs: - -- **Development**: `http://localhost:8080/callback` -- **Production**: `https://yourdomain.com/callback` +- **OAuth 2.1 Compliance** - Full OAuth 2.1 authorization server with PKCE support +- **MCP Integration** - Seamless proxy to MCP servers with user context injection +- **Multi-Provider Support** - Works with any OAuth 2.0 provider via auto-discovery +- **Database Flexibility** - PostgreSQL for production, SQLite for development -The proxy will automatically handle the OAuth flow and redirect users back to your application. - -### OAuth Scopes Explained - -#### Google OAuth Scopes - -- `openid`: Required for OpenID Connect authentication -- `profile`: Access to user's basic profile information (name, picture) -- `email`: Access to user's email address - -#### Microsoft Azure AD Scopes - -- `openid`: Required for OpenID Connect authentication -- `profile`: Access to user's basic profile information -- `email`: Access to user's email address -- `User.Read`: Access to read user's profile and basic information - -#### GitHub OAuth Scopes - -- `read:user`: Access to read user's profile information -- `user:email`: Access to read user's email addresses - -#### Custom Scopes - -You can customize the scopes based on your needs. Common additional scopes include: - -- `offline_access`: For refresh tokens (Microsoft) -- `https://www.googleapis.com/auth/userinfo.profile`: Extended Google profile access -- `repo`: GitHub repository access (if needed) - -## Setup - -### Using Docker (Recommended) - -1. **Pull the Docker image**: - - ```bash - docker pull ghcr.io/YOUR_USERNAME/mcp-oauth-proxy:latest - ``` - -2. **Run with environment variables**: - - ```bash - docker run -d \ - --name oauth-proxy \ - -p 8080:8080 \ - -e DATABASE_DSN="postgres://oauth_user:oauth_password@localhost:5432/oauth_proxy?sslmode=disable" \ - -e BASE_URL="http://localhost:8080" \ - -e SCOPES_SUPPORTED="openid,profile,email" \ - -e GOOGLE_CLIENT_ID="your-google-client-id" \ - -e GOOGLE_CLIENT_SECRET="your-google-client-secret" \ - -e MCP_SERVER_URL="http://localhost:3000" \ - -e ENCRYPTION_KEY="your-base64-encoded-32-byte-key" \ - ghcr.io/YOUR_USERNAME/mcp-oauth-proxy:latest - ``` - -### Using Docker Compose - -1. **Create a docker-compose.yml file**: - - **For PostgreSQL (production):** - - ```yaml - version: "3.8" - services: - postgres: - image: postgres:15 - environment: - POSTGRES_DB: oauth_proxy - POSTGRES_USER: oauth_user - POSTGRES_PASSWORD: oauth_password - volumes: - - postgres_data:/var/lib/postgresql/data - ports: - - "5432:5432" +## Architecture - oauth-proxy: - image: ghcr.io/obot-platform/mcp-oauth-proxy:master - environment: - DATABASE_DSN: "postgres://oauth_user:oauth_password@postgres:5432/oauth_proxy?sslmode=disable" - SCOPES_SUPPORTED: "openid,profile,email" - OAUTH_CLIENT_ID: "your-oauth-client-id" - OAUTH_CLIENT_SECRET: "your-oauth-client-secret" - OAUTH_AUTHORIZE_URL: "https://your-oauth-provider.com/oauth/authorize" - MCP_SERVER_URL: "http://localhost:3000" - ENCRYPTION_KEY: "your-base64-encoded-32-byte-key" - ports: - - "8080:8080" - depends_on: - - postgres +The proxy sits in front of your MCP server to handle OAuth 2.1 authentication and validate user identity from external providers. - volumes: - postgres_data: - ``` +Here's how it works: - **For SQLite (simpler setup):** +1. **OAuth 2.1 Flow** - When a client needs access, the proxy redirects to an external auth provider (Google, Microsoft, GitHub) to verify user identity +2. **Token Issuance** - Once authentication is complete, the proxy issues an access token back to the client +3. **MCP Auth Compliance** - Follows the MCP authentication specification and works with any compatible MCP client +4. **Request Proxying** - Validates the access token and forwards authenticated requests to your MCP server +5. **User Context** - Sends necessary headers to the MCP server about user identity and access to external services based on the OAuth scopes you configured - ```yaml - version: "3.8" - services: - oauth-proxy: - image: ghcr.io/obot-platform/mcp-oauth-proxy:master - environment: - # DATABASE_DSN not set - will use SQLite - SCOPES_SUPPORTED: "openid,profile,email" - OAUTH_CLIENT_ID: "your-oauth-client-id" - OAUTH_CLIENT_SECRET: "your-oauth-client-secret" - OAUTH_AUTHORIZE_URL: "https://your-oauth-provider.com/oauth/authorize" - MCP_SERVER_URL: "http://localhost:3000" - volumes: - - ./data:/app/data # Persist SQLite database - ports: - - "8080:8080" - ``` +## Headers Sent to MCP Server -2. **Start the services**: +When proxying requests to your MCP server, the OAuth proxy automatically injects the following headers with user information: - ```bash - docker-compose up -d - ``` +| Header | Description | Example | +| -------------------------- | ----------------------------------------- | ---------------------- | +| `X-Forwarded-User` | User ID from the OAuth provider | `12345678901234567890` | +| `X-Forwarded-Email` | User's email address | `user@example.com` | +| `X-Forwarded-Name` | User's display name | `John Doe` | +| `X-Forwarded-Access-Token` | OAuth access token for external API calls | `ya29.a0ARrdaM...` | -### Local Development +These headers allow your MCP server to: -1. **Start PostgreSQL**: +- **Identify the user** making the request +- **Personalize responses** based on user information +- **Make authenticated API calls** to external services using the access token +- **Implement user-specific logic** and access controls - ```bash - docker-compose up -d postgres - ``` +## Quick Start -2. **Create a test client**: +### Prerequisites - ```bash - go run scripts/create_client.go "postgres://oauth_user:oauth_password@localhost:5432/oauth_proxy?sslmode=disable" - ``` - -3. **Start the OAuth proxy**: - ```bash - go run main.go - ``` - -## API Endpoints - -### OAuth Endpoints - -- `GET /authorize` - OAuth authorization endpoint -- `POST /token` - OAuth token endpoint -- `POST /revoke` - OAuth token revocation endpoint - -### Metadata Endpoints +- Docker installed on your system +- An OAuth provider account (Google, Microsoft, GitHub, etc.) +- A running MCP server to proxy to -- `GET /.well-known/oauth-authorization-server` - OAuth server metadata -- `GET /.well-known/oauth-protected-resource` - Protected resource metadata +### 1. Setup OAuth Credentials -### MCP Proxy +OAuth credentials (Client ID and Client Secret) are used by the proxy to authenticate with external providers on behalf of your users. -- `ANY /*` - Proxies any request not mentioned above to MCP server with user context headers +#### Google OAuth -## OAuth Flow +1. Go to [Google Cloud Console](https://console.cloud.google.com/) and create a new project +2. Enable Google+ API in "APIs & Services" > "Library" +3. Configure OAuth consent screen and add authorized users +4. Create OAuth Client: + - Go to "Credentials" > "Create Credentials" > "OAuth 2.0 Client IDs" + - Choose "Web application" type + - Add `http://localhost:8080/callback` as redirect URI + - Copy your **Client ID** and **Client Secret** -1. **Authorization Request**: Client redirects user to `/authorize` with OAuth parameters -2. **User Approval**: User approves the authorization request -3. **Authorization Code**: Server generates and returns an authorization code -4. **Token Exchange**: Client exchanges authorization code for access and refresh tokens -5. **API Access**: Client uses access token to access protected resources - -## MCP Integration +#### Microsoft OAuth -The proxy forwards requests to the configured MCP server with the following headers: +1. Go to [Azure Portal](https://portal.azure.com/) > "Azure Active Directory" +2. Register a new application with redirect URI `http://localhost:8080/callback` +3. Configure API permissions (Microsoft Graph: `User.Read`, `Mail.Read`) +4. Create client secret and copy **Application (client) ID** and **Client Secret** -- `X-Forwarded-User`: User ID from the token -- `X-Forwarded-Email`: User email from token props -- `X-Forwarded-Name`: User name from token props -- `X-Forwarded-Access-Token`: Original access token from external provider +#### GitHub OAuth -## Testing +1. Go to GitHub Settings > Developer settings > [OAuth Apps](https://github.com/settings/applications/new) +2. Create OAuth App with callback URL `http://localhost:8080/callback` +3. Copy **Client ID** and generate **Client Secret** -### Quick Test +### 2. Setup Your MCP Server -Run the test script to test the OAuth flow: +The OAuth proxy requires a streamable HTTP MCP server. Example using Obot's Gmail MCP server: ```bash -chmod +x test_oauth.sh -./test_oauth.sh +git clone https://github.com/obot-platform/tools +cd google/gmail +uv run python -m obot_gmail_mcp.server ``` -### Comprehensive Testing +This starts the server at `http://localhost:9000/mcp/gmail`. -The project includes comprehensive testing for both PostgreSQL and SQLite databases: +### 3. Run OAuth Proxy -#### Run All Tests +#### Option A: Docker ```bash -# Run all tests (PostgreSQL) -make test - -# Run SQLite tests only -make test-sqlite - -# Run comprehensive CI tests locally -./test_sqlite_ci.sh +docker run -d --name mcp-oauth-proxy -p 8080:8080 \ + -e OAUTH_CLIENT_ID="your-client-id" \ + -e OAUTH_CLIENT_SECRET="your-client-secret" \ + -e OAUTH_AUTHORIZE_URL="https://accounts.google.com" \ + -e SCOPES_SUPPORTED="openid,email,profile,https://www.googleapis.com/auth/gmail.readonly" \ + -e MCP_SERVER_URL="http://localhost:9000/mcp/gmail" \ + -e ENCRYPTION_KEY="your-encryption-key" \ + ghcr.io/obot-platform/mcp-oauth-proxy:latest ``` -#### Database-Specific Tests +#### Option B: CLI Binary -```bash -# PostgreSQL tests (requires PostgreSQL running) -TEST_DATABASE_DSN="postgres://test:test@localhost:5432/oauth_test?sslmode=disable" go test -v ./... +1. Download from [GitHub Releases](https://github.com/obot-platform/mcp-oauth-proxy/releases) +2. Run with environment variables: -# SQLite tests (no database setup required) -DATABASE_DSN="" go test -v ./database -run TestSQLiteDatabase +```bash +export OAUTH_CLIENT_ID="your-client-id" +export OAUTH_CLIENT_SECRET="your-client-secret" +export OAUTH_AUTHORIZE_URL="https://accounts.google.com" +export SCOPES_SUPPORTED="openid,email,profile,https://www.googleapis.com/auth/gmail.readonly" +export MCP_SERVER_URL="http://localhost:9000/mcp/gmail" +export ENCRYPTION_KEY="your-encryption-key" + +./mcp-oauth-proxy ``` -#### CI Testing - -The project uses GitHub Actions for continuous integration with: - -- **PostgreSQL Testing**: Full test suite with PostgreSQL database -- **SQLite Testing**: Full test suite with SQLite database (fallback mode) -- **Code Coverage**: Coverage reports for both database types -- **Linting**: Code quality checks -- **Race Detection**: Concurrency testing -- **Build Verification**: Ensures the application builds and starts correctly - -The CI workflow runs on: - -- Push to `master` or `main` branch -- Pull requests to `master` or `main` branch - -#### Test Coverage - -The test suite covers: - -- OAuth authorization flow -- Token management and refresh -- Database operations (PostgreSQL and SQLite) -- Provider integration -- MCP proxy functionality -- Error handling and edge cases - -## Credits +## Environment Variables -The code is based on the [Cloudflare Workers OAuth Provider](https://github.com/cloudflare/workers-oauth-provider). +| Variable | Required | Description | +| --------------------- | -------- | --------------------------------------------------------- | +| `OAUTH_CLIENT_ID` | ✅ | OAuth client ID from provider | +| `OAUTH_CLIENT_SECRET` | ✅ | OAuth client secret | +| `OAUTH_AUTHORIZE_URL` | ✅ | Provider's base URL (e.g., `https://accounts.google.com`) | +| `SCOPES_SUPPORTED` | ✅ | Comma-separated OAuth scopes | +| `MCP_SERVER_URL` | ✅ | Your MCP server endpoint | +| `DATABASE_DSN` | ❌ | Database connection string (defaults to SQLite) | +| `ENCRYPTION_KEY` | ✅ | Base64-encoded 32-byte AES key | -## Security Features +You should generate a random 32-byte AES key for the `ENCRYPTION_KEY` environment variable using the following command: -- **Short-lived Access Tokens**: Access tokens expire after 1 hour by default -- **Refresh Token Rotation**: New refresh tokens are issued with each use -- **Token Revocation**: Tokens can be revoked via the revocation endpoint -- **PKCE Support**: Supports PKCE for enhanced security in public clients -- **Rate Limiting**: Built-in rate limiting to prevent abuse -- **CORS Configuration**: Configurable CORS headers for security - -## OAuth Provider Support - -The proxy supports any OAuth 2.0/OpenID Connect provider through automatic endpoint discovery. It will: - -1. **Discover Endpoints**: Automatically discover OAuth endpoints using well-known paths: - - - `/.well-known/oauth-authorization-server` - - `/.well-known/openid-configuration` - -2. **Use Discovered Endpoints**: Use the discovered authorization, token, and userinfo endpoints - -3. **Fallback**: If discovery fails, use the provided authorization URL with default endpoint assumptions - -### Supported Scopes - -The proxy supports standard OAuth scopes: - -- `openid` -- `profile` -- `email` - -### Configuration - -Set these environment variables to configure your OAuth provider: - -- `OAUTH_CLIENT_ID`: Your OAuth client ID -- `OAUTH_CLIENT_SECRET`: Your OAuth client secret -- `OAUTH_AUTHORIZE_URL`: The authorization endpoint URL from your provider - -## Development - -### Adding New Providers - -To add a new OAuth provider: - -1. Implement the `Provider` interface in `providers/provider.go` -2. Create a new provider file (e.g., `providers/github.go`) -3. Register the provider in `main.go` - -### Database Migrations - -The database schema is automatically created when the application starts. For production deployments, consider using proper database migration tools. - -### Building Docker Images +```bash +openssl rand -base64 32 +``` -The project includes a GitHub Actions workflow that automatically builds and pushes Docker images to GitHub Container Registry (GHCR) on: +**Different Auth Provider URLs:** -- Push to `main` or `master` branch -- Push of tags starting with `v` (e.g., `v1.0.0`) -- Pull requests to `main` or `master` branch (builds but doesn't push) +- Google: `https://accounts.google.com` +- Microsoft: `https://login.microsoftonline.com/common/oauth2/v2.0/authorize` +- GitHub: `https://github.com/login/oauth/authorize` -#### Manual Build +## VSCode Setup -To build the Docker image locally: +Create a `.vscode/mcp.json` file in your workspace: -```bash -docker build -t mcp-oauth-proxy . +```json +{ + "servers": { + "oauth-gmail": { + "type": "http", + "url": "http://localhost:8080/mcp/gmail" + } + } +} ``` -#### Using the GitHub Actions Image - -The workflow creates images with the following tags: +**Authentication Flow:** -- `ghcr.io/mcp-oauth-proxy/mcp-oauth-proxy:master` - Latest from master branch -- `ghcr.io/mcp-oauth-proxy/mcp-oauth-proxy:master-abc123` - Branch-specific builds +- VSCode opens browser for OAuth authentication +- Sign in with your account and grant permissions +- VSCode receives access token and communicates with the Gmail MCP server +- Use Copilot panel to interact with your emails ## License -This project is licensed under the MIT License. +This project is licensed under the Apache License 2.0. diff --git a/docs/docs/02-getting-started.md b/docs/docs/02-getting-started.md index 2d9ece8..65fa01f 100644 --- a/docs/docs/02-getting-started.md +++ b/docs/docs/02-getting-started.md @@ -208,10 +208,12 @@ You can now test your setup by using vscode MCP. - prompt to get the list of emails - you should see the list of emails -## Troubleshooting +## Example -If you are facing any issues, you can check the logs of the proxy by running the following command: +These are the example mcp servers that run with the proxy to integrate with external services. -```bash -docker logs mcp-oauth-proxy -``` +- [Gmail MCP Server](https://github.com/obot-platform/tools/tree/main/google/gmail) +- [Google Drive MCP Server](https://github.com/obot-platform/tools/tree/main/google/drive) +- [Google Calendar MCP Server](https://github.com/obot-platform/tools/tree/main/google/calendar) +- [Google Sheets MCP Server](https://github.com/obot-platform/tools/tree/main/google/sheets) +- [Outlook MCP Server](https://github.com/obot-platform/tools/tree/main/microsoft365/outlook-mcp)