Skip to main content
Glama
ahmad-act

MCP Server with Authentication

by ahmad-act

๐Ÿš€ 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.

Related MCP server: identity-aware-mcp-server

โœจ 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.

Available Tools

1 tool
echoC

Echo a simple message (no authentication required)

ParametersJSON Schema
NameRequiredDescriptionDefault
messageYes

TDQS

C2.9/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses that no authentication is required, which is a behavioral trait. However, it does not mention other potential behaviors like side effects, idempotency, or response format. For an echo tool, the behavior is simple, but the description is minimal.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, short sentence that is front-loaded and contains no unnecessary words. It is highly concise and structured effectively for quick comprehension.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the simplicity of the tool (no siblings, no output schema, one parameter), the description is adequate but lacks some details such as what the echoed response contains. It is minimally complete but leaves some ambiguity about the exact behavior.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The parameter 'message' has no description in the schema (0% coverage). The tool description does not explain what the parameter does or what format it expects. Since schema coverage is low, the description should compensate, but it fails to add any meaning beyond the parameter name.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Echo a simple message' clearly states the verb ('echo') and resource ('a simple message'), matching the tool name. It also adds the context of no authentication required. While it is somewhat tautological, it is specific enough for a simple tool.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. There are no sibling tools mentioned, and it does not specify any conditions for use or exclusion criteria. The only usage hint is 'no authentication required', which is more of a behavioral trait than usage guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 1 tool updatev0.1.0
    • First observedecho

TDQS

C2.9/5.0
Disambiguation5/5

Only one tool exists, so there is no risk of confusion between tools.

Naming Consistency5/5

With a single tool named 'echo', naming consistency is trivially maintained.

Tool Count1/5

A server named 'MCP Server with Authentication' should have multiple tools related to authentication, but instead it has only one trivial echo tool.

Completeness1/5

The server's name suggests a focus on authentication, yet the tool surface is limited to echoing messages, leaving the entire authentication domain uncovered.

Maintenance

ActivityInactive
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    MCP server for enterprise authentication and authorization โ€” JWT validation, OIDC token inspection, OAuth 2.0 introspection, and role-based access control for AI agents.
    8
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    A production-ready MCP server that authenticates agents via OAuth 2.1 Bearer tokens, validates JWTs with JWKS, enforces tool-level scopes and roles, and logs the full delegation chain.
    -
  • F
    license
    Not graded
    quality
    D
    maintenance
    A minimal MCP server with token-based authentication and SSE transport, providing greeting and echo tools for testing authentication patterns in remote MCP servers.
    -
  • F
    license
    Not graded
    quality
    C
    maintenance
    A minimal MCP server exposed over HTTP with bearer token authentication, providing echo and get_server_time tools to demonstrate transport and auth mechanics.
    -

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ahmad-act/MCP-Server-with-Authentication-and-Testing-with-Inspector'

If you have feedback or need assistance with the MCP directory API, please join our Discord server