Feishu OAuth and MCP Protocol: A Comprehensive Guide for Cloudflare Workers Deployment

In this in-depth guide, you will learn how to integrate Feishu OAuth authentication with the Model Context Protocol (MCP) server, deploy it on Cloudflare Workers, and connect via popular MCP clients. This article covers installation, configuration, security, and advanced customization.

Table of Contents

  1. Introduction to MCP and Feishu OAuth
  2. Key Benefits and Differentiators
  3. Prerequisites and Environment Setup
  4. Installation and Local Development
  5. Production Deployment on Cloudflare Workers
  6. Configuring Feishu OAuth and Redirect URIs
  7. Client Integration: Inspector, Cursor, ChatWise
  8. Access Control and Security Best Practices
  9. Advanced Features and Roadmap
  10. MCP Server Architecture and Components
  11. Troubleshooting Common Issues
  12. Conclusion and Next Steps

1. Introduction to MCP and Feishu OAuth

The Model Context Protocol (MCP) enables AI tools to communicate with servers via a standardized interface. Originally designed to work with GitHub OAuth, MCP can be adapted to use Feishu OAuth, offering seamless authentication for enterprise users in China and beyond. By deploying an MCP server on Cloudflare Workers, you leverage global edge infrastructure for low latency and high availability.

What is MCP?

MCP defines a set of HTTP endpoints and message formats that AI clients use to request tool execution, fetch context, and send updates. It uses Server-Sent Events (SSE) to maintain an open channel for real-time interactions. Key components:

  • SSE Endpoint: Keeps a live connection between client and server.
  • Tool Registry: Defines available tools and their I/O schemas.
  • Durable Objects: Store per-user state and context.

Why Feishu OAuth?

Feishu (also known as Lark internationally) is a popular collaboration platform in China, offering secure identity management and granular permission controls. Integrating Feishu OAuth ensures enterprises can authenticate users with their existing corporate credentials, enforce single sign-on (SSO), and comply with organizational security policies.

2. Key Benefits and Differentiators

This Feishu-based MCP server project diverges from the official example in three main ways:

  1. Zero-Configuration Experience: Users do not need to manage access token refresh logic; the server handles it automatically.
  2. Optimized Tool Suite: Complex operations like nested block creation and batch updates have been refactored for performance and reliability in clients such as Cursor.
  3. Global Edge Deployment: By leveraging Cloudflare Workers and Durable Objects, the server scales to millions of users with minimal latency.

3. Prerequisites and Environment Setup

Before diving into code, ensure you have the following:

  • Node.js 18+ and npm installed.
  • A Cloudflare account with Workers and KV namespace privileges.
  • A Feishu developer account to create an application and obtain credentials.

4. Installation and Local Development

Before deploying to production, you can run the MCP server locally to verify functionality and iterate quickly.

4.1 Clone and Install

  1. Clone the repository

    git clone <repository-url>
    cd my-mcp-server
    
  2. Install dependencies

    npm install
    

4.2 Configure Environment Variables

Create a file named .dev.vars in the project root to store your development credentials:

FEISHU_APP_ID=your_dev_feishu_app_id
FEISHU_APP_SECRET=your_dev_feishu_app_secret
COOKIE_ENCRYPTION_KEY=any_random_string_here

Note: Use a strong random string for COOKIE_ENCRYPTION_KEY, for example generated via openssl rand -hex 32.

4.3 Local Redirect URI

In your Feishu Developer Console, navigate to Security Settings and add the following redirect URI:

http://localhost:8788/callback

4.4 Start the Local Server

Use Wrangler to run your server locally, emulating the Cloudflare Workers environment:

wrangler dev

By default, your MCP server will listen on http://localhost:8788. You can now open your MCP client (Inspector, Cursor) and point it to http://localhost:8788/sse to authenticate via Feishu and test tool execution.

4.4.1 Verifying Authentication Flow

  1. Connect via an MCP client to the SSE endpoint.
  2. You should be redirected to Feishu’s login page.
  3. After granting permissions, Feishu will redirect back to your local callback endpoint.
  4. The server will exchange the authorization code for an access token, store it in KV, and establish an SSE connection.

5. Production Deployment on Cloudflare Workers

Once local testing is successful, deploy the server globally to handle real traffic.

5.1 Configure Secrets

Add your Feishu credentials and encryption key to your Cloudflare account via Wrangler:

wrangler secret put FEISHU_APP_ID
wrangler secret put FEISHU_APP_SECRET
wrangler secret put COOKIE_ENCRYPTION_KEY

These commands will prompt you to enter each secret value interactively.

5.2 Create KV Namespace

Cloudflare Workers KV provides persistent storage for user tokens:

wrangler kv:namespace create "OAUTH_KV"

Note the namespace ID returned by this command, and add it to your wrangler.toml under kv_namespaces:

kv_namespaces = [
  { binding = "OAUTH_KV", id = "<your-namespace-id>" }
]

5.3 Update Configuration

In wrangler.toml, ensure the following fields are correctly set:

name = "feishu-mcp-server"
type = "javascript"
account_id = "<your-cloudflare-account-id>"
workers_dev = true

[vars]
# Other global vars if needed

[kv_namespaces]
# Already configured above

5.4 Deploy Command

Run the deploy command to push your code and configuration to Cloudflare:

wrangler deploy

On success, Wrangler will print the deployed subdomain:

✨ Success! Published to https://feishu-mcp-server.<your-subdomain>.workers.dev

5.5 Verify Production Endpoint

  1. In your Feishu Developer Console, update the Redirect URI to:

    https://feishu-mcp-server.<your-subdomain>.workers.dev/callback
    
  2. Use an MCP client to connect to:

    https://feishu-mcp-server.<your-subdomain>.workers.dev/sse
    
  3. Confirm that the SSE connection remains stable and tools respond as expected.


6. Configuring Feishu OAuth and Redirect URIs

Proper OAuth configuration is crucial for secure authentication and smooth user experience. This section covers how to set up your Feishu application and configure redirect endpoints both locally and in production.

6.1 Creating and Configuring a Feishu Application

  1. Log in to Feishu Developer Console: Visit https://open.feishu.cn/ and sign in with your corporate credentials.

  2. Create New App:

    • Select Create App and choose Custom App.
    • Provide an app name (e.g., “Feishu MCP Server”).
  3. Set Permissions:

    • Navigate to Permissions & Features.

    • Add the following scopes:

      • auth:user.id:read – Read user IDs.
      • task:task:read – Read task information (optional).
      • offline_access – Obtain refresh tokens.
      • user_profile – Read basic user profile information.
  4. Obtain App Credentials:

    • Under Basic Settings, copy your App ID and App Secret.

6.2 Redirect URI Configuration

OAuth requires exact redirect URIs to be whitelisted. Any mismatch will cause authentication to fail.

6.2.1 Local Environment

  • URI: http://localhost:8788/callback
  • Add this URI under Security SettingsRedirect URIs in the Feishu console.

6.2.2 Production Environment

  • URI: https://feishu-mcp-server.<your-subdomain>.workers.dev/callback
  • After deploying, update the redirect URI in the Feishu console to use your live domain.

Tip: OAuth errors often stem from minor typos in the redirect URI. Always copy-paste the exact URL printed by Wrangler.

6.3 Verifying OAuth Setup

  1. Start your server (locally or in production).

  2. Open the SSE endpoint in a browser:

    • Local: http://localhost:8788/sse
    • Prod: https://feishu-mcp-server.<your-subdomain>.workers.dev/sse
  3. You should be redirected to Feishu’s login page.

  4. After approving, you will be redirected back to <callback> with a code in the query string.

  5. Confirm that no errors appear in your server logs and that SSE connection initializes.


7. Client Integration: Inspector, Cursor, ChatWise

This section demonstrates how to connect various MCP clients to your Feishu-based MCP server.

7.1 MCP Inspector

The MCP Inspector is a CLI tool for testing MCP endpoints.

  1. Install Inspector:

    npm install -g @modelcontextprotocol/inspector
    
  2. Launch Inspector with your SSE URL:

    inspector --url http://localhost:8788/sse
    # or for production:
    inspector --url https://feishu-mcp-server.<subdomain>.workers.dev/sse
    
  3. Follow prompts to authenticate via Feishu.

  4. Once connected, you can issue MCP tool commands interactively.

7.2 Cursor Client

Cursor is a GUI-based MCP client with built-in integration buttons.

  1. Open Cursor and navigate to SettingsMCP Servers.

  2. Click Add Server and choose Custom.

  3. Enter:

    • Name: Feishu MCP
    • URL: http://localhost:8788/sse (or production URL)
  4. Save and click Connect. Cursor will prompt for Feishu login.

  5. Once authenticated, you can use MCP tools directly within Cursor.

Alternatively, use the one-click install badge:

Install MCP Server

7.3 ChatWise Integration

ChatWise supports MCP servers via stdio commands.

  1. Open ChatWise preferences and navigate to ToolsAdd Tool.

  2. Choose Shell Command:

    • Name: Feishu MCP
    • Command: npx -y mcp-remote https://feishu-mcp-server.<subdomain>.workers.dev/sse
  3. Save and invoke the tool in any chat.

  4. The first invocation will open Feishu’s login; grant permissions and continue.


8. Access Control and Security Best Practices

Ensuring secure access to your MCP server is paramount for protecting user data and maintaining service integrity. Below are key considerations and recommendations.

8.1 Role-Based Access Control (RBAC)

Implement fine-grained permissions by defining roles, such as admin, developer, and end-user. Use MCP tools to verify user identity and enforce access:

  • Admin: Full CRUD access to all tools and configurations.
  • Developer: Permission to deploy new tools and view logs.
  • End-User: Only allowed to execute pre-approved tools.

Leverage Feishu’s user groups and mapping to assign roles within your Worker code.

8.2 Token Management

  • Access Tokens: Short-lived tokens stored in KV with expiration metadata.
  • Refresh Tokens: Securely stored and rotated automatically by the server.
  • Encryption: Use COOKIE_ENCRYPTION_KEY to encrypt tokens at rest.

8.3 Data Privacy

  • Least Privilege: Only request minimal OAuth scopes necessary for functionality.
  • Logging: Mask sensitive fields in logs; store logs in a separate, secured KV namespace or external log service.
  • HTTPS Everywhere: Enforce TLS for all client-server communication.

8.4 Rate Limiting and Abuse Prevention

Implement per-user and per-IP rate limits within your Worker:

  • Allow a burst of requests (e.g., 10 tools per minute) followed by a steady threshold (e.g., 1 request/sec).
  • Return HTTP 429 status for rate-exceeded clients.
  • Integrate with Cloudflare Rate Limiting if needed.

9. Advanced Features and Roadmap

Future enhancements can expand functionality and improve user experience:

9.1 Electronic Spreadsheet (Sheets) Integration

  • Basic Operations: Create, rename, delete sheets.
  • Cell-Level CRUD: Read/write cell values and formulas.
  • Formula Engine: Server-side evaluation of common functions (SUM, AVERAGE).
  • Charting API: Generate and embed charts via MCP tools.

9.2 Multidimensional Database (Bitable)

  • Record Management: Create, query, update, delete records.
  • Field Types: Support text, number, date, attachment fields.
  • View Filters: Build filtered and grouped views.
  • Automation Rules: Server-side triggers to enforce data workflows.

9.3 Collaboration Features

  • Real-Time Co-Editing: Use Durable Objects to broadcast document changes.
  • Comments & Mentions: MCP tools for threaded comments and @mentions.

9.4 AI-Powered Enhancements

  • Contextual Suggestions: Analyze document content and recommend related resources.
  • Auto Summarization: Provide concise summaries via an AI tool.

10. MCP Server Architecture and Components

A robust architecture underpins reliability and scalability.

10.1 OAuth Provider Module

  • Endpoint: /oauth/*

  • Responsibilities:

    • Handle authorization code exchange.
    • Manage token refresh workflows.
    • Validate scopes and permissions.

10.2 Durable MCP Module

  • Durable Objects:

    • One object per user session.
    • Store user context and token metadata.
  • API Handlers:

    • /sse: SSE connection for live events.
    • /tools: Tool registry and invocation endpoint.

10.3 Worker Scripts

  • Bundled JavaScript modules:

    • index.js: Entry point for HTTP routing.
    • oauth.js: OAuth logic.
    • mcp.js: MCP protocol handlers.

10.4 Storage Layers

  • Workers KV: Persistent storage for tokens and small state.
  • Durable Objects: Ephemeral, fast-access context storage.

11. Troubleshooting Common Issues

11.1 OAuth Failures

  • Invalid Redirect URI: Verify exact match between Feishu console and Worker callback.
  • Mismatched Scopes: Ensure requested scopes match granted scopes.
  • Clock Skew: Sync server time; use NTP.

11.2 SSE Connection Drops

  • Ping/Pong Keepalive: Implement periodic comments in SSE stream.
  • Proxy Configuration: Ensure corporate proxies allow text/event-stream.

11.3 Token Expiration Errors

  • Confirm automatic refresh logic in oauth.js is invoked before token expiry.
  • Inspect KV entries to verify refresh token validity and timestamps.

11.4 Performance Bottlenecks

  • Bundle size: Use wrangler config to enable minification.
  • Cold starts: Pre-warm Durable Objects using scheduled triggers.

12. Conclusion and Next Steps

In this guide, you’ve learned how to:

  • Set up Feishu OAuth for secure SSO.
  • Deploy an MCP server on Cloudflare Workers.
  • Integrate with popular clients like Inspector, Cursor, and ChatWise.
  • Implement robust access control, rate limiting, and token management.
  • Plan future features for spreadsheets, multidimensional tables, and AI enhancements.

By following these best practices, you can build a scalable, secure MCP-based platform that meets enterprise needs. Start experimenting with custom tools and workflows to unlock the full potential of MCP and Feishu integration.

Ready to Get Started?

  1. Clone the repo and follow the local setup in Section 4.
  2. Configure your Feishu app for OAuth as detailed in Section 6.
  3. Deploy globally with wrangler deploy and connect via your preferred MCP client.