MCP Server with Authentication

MCP Server with Authentication

Implements a secure MCP server with API Key and JWT authentication, providing tools like echo, login, secure_action, and admin_action. Includes MCP Inspector integration for testing and debugging.

Category
访问服务器

README

🚀 MCP Server with Authentication and Testing with Inspector

This project implements a Model Context Protocol (MCP) server with two authentication mechanisms: API Key Authentication and JWT (JSON Web Token) Authentication. It provides a robust framework for handling authenticated requests with comprehensive error handling and logging, suitable for production environments. The server supports tools like echo, login, secure_action, and admin_action, with authentication enforced where required.

📚 Table of Contents

  1. 🚀 Project Overview

  2. 🎯 Purpose

  3. ✨ Features

  4. 🗂️ Project Structure

  5. ✅ Prerequisites

  6. ⚙️ Installation

  7. 🧩 Packages

  8. 🚦 Usage

  9. 🔄 Workflow

  10. 🩵 Troubleshooting

🎯 Purpose

The purpose of this project is to demonstrate secure MCP server implementations with two distinct authentication methods:

  • 🔑 API Key Authentication: Validates requests using predefined API keys.
  • 🛡️ JWT Authentication: Uses JSON Web Tokens for user authentication and permission-based access control.

This project is designed for developers who need a secure, scalable, and extensible MCP server with robust debugging and logging capabilities.

✨ Features

  • 🔑 API Key Authentication:

    • Validates requests using a set of predefined API keys.
    • Supports key extraction from arguments, metadata, or environment variables.
    • Simple echo tool for demonstration.
  • 🛡️ JWT Authentication:

    • Supports user authentication via username/password to generate JWT tokens.
    • Enforces permission-based access control (read, write, admin).
    • Includes tools: login, echo, secure_action, and admin_action.
    • Configurable token expiry (default: 24 hours).
    • Token extraction from arguments, metadata, or environment variables.
  • ⚠️ Robust Error Handling:

    • Custom McpError for consistent error responses.
    • Detailed logging of errors and server events.
  • 📝 Logging:

    • Configurable logging to both console and rotating log files.
    • Log rotation based on file size (5MB, with 5 backups).
    • Automatic cleanup of old log files based on age.
  • 🔍 MCP Inspector Integration:

    • Compatible with MCP Inspector for testing and debugging.
    • Supports debugging via --debug flag.

🗂️ Project Structure

/
├── src/
│   ├── config/
│   │   ├── __init__.py
│   │   ├── app_settings.py                     # Configuration for environment variables and settings
│   │   └── logging_config.py                   # Logging setup with file rotation
│   ├── mcp-server-with-stdio-api-key-auth.py   # API Key Authentication server
│   ├── mcp-server-with-stdio-auth2-auth.py     # To Do
│   └── mcp-server-with-stdio-jwt-key-auth.py   # JWT Authentication server
├── pyproject.toml                              # Project documentation
└── README.md                                   # Python dependencies

✅ Prerequisites

  • Python: Version 3.13 or higher
  • uv: Used for managing Python virtual environments
  • Node.js: Required for running MCP Inspector
  • NPM: Required to run MCP Inspector
  • Operating System: Windows, macOS, or Linux

⚙️ Installation

  1. 📥 Clone the Repository:

    git clone https://github.com/ahmad-act/MCP-Server-with-Authentication-and-Testing-with-Inspector.git
    cd MCP-Server-with-Authentication-and-Testing-with-Inspector
    
  2. 🪄 Set Up a Virtual Environment (recommended):

    uv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  3. 📦 Install Dependencies:

    uv sync
    

🧩 Packages

The following Python packages are required:

mcp[cli]>=1.10.1
PyJWT>=2.8.0
python-dotenv>=1.0.0

👉 Install them using:

uv add mcp[cli] PyJWT python-dotenv

🚦 Usage

1️⃣ MCP Server with Stdio and API Key (mcp-server-with-stdio-api-key-auth.py)

▶️ Run the MCP Server:

⚠️ You do not need to manually run the MCP server for stdio transport. MCP Inspector runs the MCP Server for stdio transport.

▶️ Run the MCP Inspector:

The stdio server is typically launched by the MCP Inspector, not manually. Run the Inspector with the following command, add -e environment variable and adjusting the --directory path to your src/ directory:

npx @modelcontextprotocol/inspector uv -e MCP_API_KEY=sk-1234567890abcdef --directory '<your-src-directory>/src' run mcp-server-with-stdio-api-key-auth.py --debug

MCP Inspector Run

🌐 Open the MCP Inspector:

Open the link http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=XXXXXXXXXXXXXXXXXX with its token in your browser:

MCP Inspector Use

🧪 Using the MCP Inspector

  1. After running the above command, the Inspector will start and automatically connect to the stdio-based server.

  2. In the Inspector UI (http://127.0.0.1:6274), inspect the available tools (e.g., echo).

  3. Test the echo tool:

    • Input:
    {
      "method": "call_tool",
      "params": {
        "name": "echo",
        "arguments": {
          "message": "test",
          "_api_key": "sk-1234567890abcdef"
        }
      }
    }
    

    Expected Response:

    {
      "result": [
        {
          "type": "text",
          "text": "Echo: test"
        }
      ]
    }
    

    MCP Inspector Use MCP Inspector Use MCP Inspector Use

2️⃣ MCP Server with Stdio and API Key (mcp-server-with-stdio-jwt-key-auth.py)

▶️ Run the MCP Server:

⚠️ You do not need to manually run the MCP server for stdio transport. MCP Inspector will launch the server automatically.

▶️ Run the MCP Inspector:

The stdio server is typically launched by the MCP Inspector, not manually. Run the Inspector with the following command, adjusting the --directory path to your src/ directory:

npx @modelcontextprotocol/inspector uv --directory '<your-src-directory>\src' run mcp-server-with-stdio-jwt-key-auth.py --debug

MCP Inspector Run

🌐 Open the MCP Inspector:

Open the link http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=XXXXXXXXXXXXXXXXXX with its token in your browser:

MCP Inspector Use

🧪 Using the MCP Inspector

  1. After running the above command, the Inspector will start and automatically connect to the stdio-based server.

  2. Usage Flow:

    • Step 1: Login to Get JWT Token:

      {
        "method": "call_tool",
        "params": {
          "name": "login",
          "arguments": {
            "username": "user1",
            "password": "password123"
          }
        }
      }
      

      Response:

      {
        "result": [
          {
            "type": "text",
            "text": "Login successful! JWT Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
          }
        ]
      }
      
    • Step 2: Use JWT Token for Authenticated Requests:

      {
        "method": "call_tool",
        "params": {
          "name": "echo",
          "arguments": {
            "message": "test",
            "_jwt_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
          }
        }
      }
      

      Response:

      {
        "result": [
          {
            "type": "text",
            "text": "Echo (authenticated as user1): test"
          }
        ]
      }
      

    MCP Inspector Use MCP Inspector Use MCP Inspector Use MCP Inspector Use

3️⃣ MCP Server with Stdio and Auth2 (mcp-server-with-stdio-auth2-auth.py)

🚧 To Do


🔄 Workflow

  1. 🔑 API Key Authentication:

    • The server checks for a valid API key in the request arguments, metadata, or environment variables.
    • If valid, the request is processed; otherwise, an error is returned.
    • The echo tool demonstrates basic functionality.
  2. 🛡️ JWT Authentication:

    • Users first call the login tool with valid credentials to obtain a JWT token.
    • The token is used in subsequent requests for tools like echo, secure_action, or admin_action.
    • Permissions (read, write, admin) are checked for each tool.
    • Tokens expire after 24 hours (configurable).
  3. 📝 Logging:

    • Logs are written to both the console and a rotating log file in the logs directory.
    • Old log files are cleaned up based on a specified retention period.
  4. 🔍 Testing with MCP Inspector:

    • Use MCP Inspector to interact with the server via a web interface.
    • Debug mode (--debug) provides detailed output for troubleshooting.

🩵 Troubleshooting

  • 🚫 Invalid API Key:

    • Ensure the API key is one of: sk-1234567890abcdef, sk-abcdef1234567890, sk-test123456789.
    • Check environment variable MCP_API_KEY or request arguments.
  • ⚠️ Invalid JWT Token:

    • Verify the token is not expired (valid for 24 hours).
    • Ensure the correct JWT_SECRET is set.
    • Check username/password for login tool.
  • 🔒 Permission Errors:

    • Ensure the user has the required permissions (read, write, or admin) for the requested tool.
  • 📝 Log Files:

    • Check the logs directory for detailed error messages.
    • Logs are named in the format YYYYMM.log.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选